stalkeyefly has asked for the wisdom of the Perl Monks concerning the following question:
I have a file in the form
id1 val1
id1 val2
id2 val1
id2 val3
id3 val2
id3 val3
id3 val4
I'm forming a HoA that associates the ids which are unique with their values that are not. I want a user to enter an id (or ids). The ids are then looked up in the hash and the array of values associated with each id is printed.
Okay so my code runs - it does hang but thats due to the silly size of the file. I get a very long list of
The first method below but commented out - pints the first val only.
print "$user: @{ $p2i{$user} }\n";
The second method prints the ref to the array .i.e. ARRAY(0xf4d4a88)
The full code is below. I think my problem is that I'm not dereferencing the array correctly....print "$user is in the hash. \n"; @user_array = split(/ /, $p2i{$user}); foreach (@user_array) { print "$_\n"; }
Cheers#!/usr/bin/perl use strict; use warnings; my $file = "p2iextact.txt"; my %p2i; my @user_array; my $sp; my $ipr; my $key; my $user; # creates hash of arrays open(FILE, "p2iextact.txt") || die "can't open file"; while(<FILE>) { chomp; ($sp, $ipr) = split; if (exists $p2i{$sp}) { push @{$p2i{sp}}, $ipr; } else { $p2i{$sp}= [$ipr]; } } close FILE; # test to see if hash created correctly foreach $key (sort keys %p2i) { print "$key\t$p2i{$key}\n"; } print "Please enter an ID: "; chomp( $user = <STDIN>); # try to used uppercaes function to avoid errors $user = uc($user); #see if id is in the hash and print @vals if (exists $p2i{$user}) { print "$user is in the hash. \n";if (exists $p2i{$user}) { print "$user is in the hash. \n"; @user_array = split(/ /, $p2i{$user}); foreach (@user_array) { print "$_\n"; } # print "$user: @{ $p2i{$user} }\n"; # only retieves one value even when more than one #val even +if there are multiple } else { print "$user is not in the hash.\n"; } exit;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re:de-ref an array from HoA
by davidj (Priest) on Jun 17, 2004 at 12:21 UTC | |
by stalkeyefly (Novice) on Jun 17, 2004 at 14:37 UTC | |
|
Re:
by periapt (Hermit) on Jun 17, 2004 at 11:59 UTC | |
|
Re: de-ref an array from HoA
by pelagic (Priest) on Jun 17, 2004 at 11:18 UTC |