Thanks Marshall for the valuable input. Your code is crisp and easy to understand. I appreciate the tips provided by you, Corion and Hauke Although I am not able to figure out why it doesnt display the result for the last name from STDIN. In the example shown, the result for last element "john" is missing.
Input: 4 tom 332211 harry 112233 ryan 445566 john 334455 jay harry ryan kelly john Output: Not found harry=112233 ryan=445566 Not found Code: use strict; use warnings; use Data::Dumper; my %phone_num; while (my $line = <STDIN>) { my $name; my $phone; next unless ($name, $phone) = $line =~/^\s*([a-zA-Z]+)\s+(\d+)*/; if (defined $phone) # A new phone book entry { $phone_num{$name} = $phone; } else # Just a name. { if ($phone_num{$name}) { print "$name=$phone_num{$name}\n"; } else { print "Not found\n"; } } }
The reason why I used a for loop inside a for loop was to get the correct value index to properly map name value pairs. Once I spliced the array N, I only have the names which needs to be checked for phonebook entry inside @N. Then I checked @N against the keys of the hash inside @data. Now the index i for @N need not be same for @data, that's why used another for loop to match the correct key-value pairs once the if condition i.e. grep holds good. This kind of approach makes it a lot more cumbersome. Your algo and approach seems to be way better and fast. Thanks!
In reply to Re^2: Perl program to look into the phone directory and in case of a match, print the name along with the number
by dk27
in thread Perl program to look into the phone directory and in case of a match, print the name along with the number
by dk27
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |