There are a couple of issues with your code
In your first while loop, you have a bareword sp where you meant $sp. The effect of this would be to assign only one value to each key in the file. Second and subsequent values for a key would be assigned to $p2i{sp}.
In your first foreach loop you try to print the value of $p2i{$key} which is simply a reference to the array you have stored the values in. You have to dereference this value into an array with @{$p2i{$key}}
You have some duplicative code in your if(exists...) loop. You can print the values of the array in $p2i{$user} with the simple foreach loop.
For more information on references, take a look at
perldoc -m perlreftut and
perldoc -m perlref
while(<FILE>) {
chomp;
($sp, $ipr) = split;
if (exists $p2i{$sp}) {
push @{$p2i{$sp}}, $ipr;
# 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 "$key\t@{$p2i{$key}}\n";
}
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});
# @user_array = split(/ /, $p2i{$user});
# foreach (@user_array) {
# print "$_\n";
# }
foreach (@{$p2i{$user}}){
print "$_ ";
}
print "\n";
# print "$user: @{ $p2i{$user} }\n";
# only retieves one value even when more than one #val even if the
+re are multiple
# }
}
else {
print "$user is not in the hash.\n";
}
exit;
PJ
We are drowning in information and starving for knowledge - Rutherford D. Rogers
What good is knowledge if you have to pull teeth to get it - anonymous
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.