首页 > 解决方案 > Why is the perl hash overwriting previous data?

问题描述

So, I'm writing data into my hash which is %errordata. It looks like this

sub openfile
{
 if (open my $data, "<", $filename)
   {
    my $line = <$data>;
    print "Error: $line";
    my $dir = cwd;
    print "$dir\n";
    $errordata{$line} = $dir;
    while (my($keys,$values) = each %errordata) {
     print "$keys in $values\n";
    }
}

The first two print output that I got looks something like this

FIRST 
ERROR: quick brown fox
/abc/efg/hij/klm
SECOND
ERROR: quick brown fox
/abc/efg/hij/gvb

But every time it encounters the same output it overwrites it but I want to save the path because it may be different.

FIRST 
quick brown fox in /abc/efg/hij/klm
SECOND
quick brown fox in /abc/efg/hij/klm

Should I use push (@{%hash{"KEYNAME"} }, "new value") ? If so, can anyone elaborate on this? I'm not sure how to go on about this. Any suggestions would be helpful. Thank you!

标签: perlhashkey

解决方案


Perl hash assumes that each key is unique. If you would like to store more than one value or data structure under one key you need apply some logic how to achieve desired result.

Please see the following demo code to sort teachers and students from incoming data.

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my %people;
my $re = qr/(\S+)\s+(.*)/;

while( <DATA> ) {
    my($title,$name) = /$re/;
    push @{$people{$title}}, $name;
}

say Dumper(\%people);

while( my($title,$group) = each %people ) {
    say ucfirst $title . ':';
    say "\t$_" for @{$group};
}

__DATA__
teacher Alex Trump
student Amanda Torry
student Nick Popler
student Jonny Sleeper
student Natalie Simpson
teacher George Magic
student Tom Smarty
teacher Pat Golder

Output

$VAR1 = {
          'teacher' => [
                         'Alex Trump',
                         'George Magic',
                         'Pat Golder'
                       ],
          'student' => [
                         'Amanda Torry',
                         'Nick Popler',
                         'Jonny Sleeper',
                         'Natalie Simpson',
                         'Tom Smarty'
                       ]
        };

Teacher:
        Alex Trump
        George Magic
        Pat Golder
Student:
        Amanda Torry
        Nick Popler
        Jonny Sleeper
        Natalie Simpson
        Tom Smarty

推荐阅读