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

Your code works fine, although you do create two variables $key and $value that you don't use or need.

Also, a simpler test than looping on the keys is to just test if the key exists in the hash:

use strict; use warnings; my %family_name = ( "Alis" => "Williams", "Sara" => "McAwesome", "Serena" => "Anderson", ); print "Enter a name to print it's family name : \n"; chomp(my $name = <STDIN>); if ($family_name{$name}) { print "$name is already there, and its family name is $family_name +{$name} "; }

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:04 UTC
    totally agree! both values are not needed, I forgot to remove them while modifying the same file to create different scenarios! I believe in your alternative solution, the if condition works the same as 'exist' the return value from that is 1 when the key is actually found, and 0 if not. hence, it would print the equivalent value for that particular key if it exists! correct me if I'm wrong! thanks for the reply my friend!