http://www.perlmonks.org?node_id=897596


in reply to Comparing Hash's key to an <STDIN> and print it's corresponding value

In addition to kennethk and wind valuable input, I have the following comments about your code...
#Consider the output of the following my %family_name = ( "Alis" => "Williams", "Sara" => "McAwesome", "Serena" => "Anderson", ); my $key = keys %family_name; print $key; print "\n"; my $val = values %family_name; print $val; print "\n"; my @keys = keys %family_name; print "@keys\n"; my @values = values %family_name; print "@values\n";
So, availing of the context property in Perl we can achieve what you sought in a TIMTOWTDI yet somewhat convoluted manner. Just as a proof of concept and maybe a review of some of the things you have studies so far consider the following code... Comments are duly provided
use strict; use warnings; #The hash is populated as in the OP code above #The user is prompted to enter a name my @keys = keys %family_name; my @values = values %family_name; #The arrays members are in the same order the hash #is stored in the memory and not necessarily the #order in which the hash has been populated. my $index; for(my $i = 0; $i<=$#keys; $i++){ #looping through @keys if($name eq $keys[$i]){ $index = $i; #to retain the iterator value to $index retHashVal($name, $index); } } sub retHashVal{ my ($n,$i) = @_; print "$n is already there and her family name is $values[$i]\ +n"; }


Excellence is an Endeavor of Persistence. A Year-Old Monk :D .

Replies are listed 'Best First'.
Re^2: Comparing Hash's key to an <STDIN> and print it's corresponding value
by xxArwaxx (Novice) on Apr 07, 2011 at 13:32 UTC
    wow! for a first reply, it's pretty much impressive how much I'm benefiting from these brain storming, in both, Perl and grammatical sense! :P well, I was like "what if the person is he, then what if he is a she" then I thought of replacing it with an "it" for time saving purposes as my main concern was actually running the code! lol I totally agree with what you just mentioned, because I've been in the situation of printing the number of elements there and not only once but in the same number as key-value pairs was there! after fixing it, I can understand the context concept you're talking about! I understood it even more, from the latter example you proposed! loved how you made use of arrays to print the index of the key that has been entered by the user, and then printing it's value! what's interesting even more in your code and might need a bit of elaboration, if you don't mind me, is that part when you invoke the retHashVal and both parameters are scalars, while in it's body you would use the array's default variable in assigning to $n and $i .. how things are working there? depending on context I'd say that @_ would be converted implicitly to a scalar, is this how it goes in this case?