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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.