Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Currently my code is printing $id and # of times $id is in @data2.

for ( @data ) { my ($id,$name,$ref) = split /,/; # You may wish to add some error checking to make sure the # hash key $id does not already exist $keyhash{$id} = { NAME => $name, REF => $ref#, #MANY => [], } } for ( @data2 ) { my ($id,$name,$ref) = split /,/; # Warn and do nothing if a record is found for which the # $id is not already in %keyhash unless ( defined( $keyhash{$id} ) ) { warn "No such record $id!\n"; next; } push @{$keyhash{$id}{MANY}}, [ $name, $ref ]; } ##Although you may want MANY to be a hash - it really depends on how y +ou want to use your data later. ##Finally, to extract the number of records for each ID, ##print header print "Customer #of docs\n"; # A little something to get the plurality correct for ( keys %keyhash ) { my $num = @{$keyhash{$_}{MANY}}; printf "%s appeared %d %s\n", $_, $num, $num > 1 ? "times" : "time"; }


When the script is executed it prints:

No such record 4!

No such record 5!

Customer #of docs

appeared 0 time

22 appeared 0 time

1 appeared 3 times

2 appeared 3 times

3 appeared 4 times

How can I print $name instead of $id? How can I get other variables if added to the array?

Thank you.

Replies are listed 'Best First'.
Re: hash me a few variables
by busunsl (Vicar) on Mar 20, 2001 at 04:10 UTC
    Try:
    printf "%s appeared %d %s\n", $keyhash->{NAME}, $num, ...
    Have a look at perldoc perlref
Re: hash me a few variables
by buckaduck (Chaplain) on Mar 20, 2001 at 04:15 UTC
    Is there some reason that you have comment characters in the code where you define your hash? This may be part of the problem. $keyhash{$id}{MANY} doesn't exist!
    $keyhash{$id} = { NAME => $name, REF => $ref#, <--- HERE? #MANY => [], <--- AND HERE? };
    buckaduck
      I forgot to remove them after I was testing some other code. Thanks for reminding me.
        But removing the comments didn't help nor did adding $keyhash->{NAME},
        I'm confused.