in reply to Perl program to look into the phone directory and in case of a match, print the name along with the number

Hi dk27,

First, some general things: I would suggest using proper indentation to make your code easier to read. See perltidy for a program that does it for you. Also, Use strict and warnings, it is a good habit to get into. (Update: Your code is simply missing the declarations my @data; my @value; to make it work under strict.)

Note that it is not necessary to read the entire input into an array and then process it. You can read the input line-by-line using a while (<>) loop (documented in I/O Operators). Also, you can read a single line of input (such as the number of entries) using <> in scalar context (see example below).

There appears to be some munging going on that your sample input does not explain. For example, what is split( /[\[\],]/, $s ) for?

You appear to first be checking whether an entry exists in the array @data using grep, which looks though the entire array, and if there is a match with the regex /^$N[$i]/, you search the entire @data array a second time, looking for an exact match. Either the first or the second check is not necessary, and note that in Perl, hashes are much easier to use for exact string lookups.

Here's how I might have written the same script:

  1. Read the number of phone book entries using my $numentries = <>;.
  2. Read the phone book entries themselves using a while (<>) loop, using last to break out of the loop when the number of entries has been reached. Each line of input can be broken down into name and number using split, and then stored in a hash, e.g. $phonedirectory{$name} = $number;.
  3. Read the rest of the input using a second while (<>) loop, using simple hash lookups ($phonedirectory{$name}) to fetch the numbers. You can use exists to see if a certain entry exists in the hash.

Hope this helps,
-- Hauke D