in reply to Perl program to look into the phone directory and in case of a match, print the name along with the number
I guess it is nice that the number of phone book entries appears first. However, I consider it "noise" and throw it away. There is no need to use it and this would not be known in any "real" phone book application.
A valid line consists of a name, some space and optionally a phone number.
If we have the optional phone number, then this line is a new phone book entry. If it is just a name, then just look up the number in the phone_num hash and print the result. There is no need to "keep track of the sections".
Now of course in a "real" application, this would be more complicated because for example you would have to allow for there to be more than one "john" each with a different phone number.#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %phone_num; while (my $line =<DATA>) { my $name; my $phone; # this throws away malformed lines, like "4 (represents..." 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. Look up its phone number { if ($phone_num{$name}) { print "$name $phone_num{$name}\n"; } else { print "Not found\n"; } } } print "\nJust to show what phone_num hash is:\n"; print Dumper \%phone_num; =Program Output: Not found john 334455 Not found Just to show what phone_num hash is: $VAR1 = { 'harry' => '112233', 'tom' => '332211', 'ryan' => '445566', 'john' => '334455' }; =cut __DATA__ 4 (represents no. of entries in phone directory) tom 332211 harry 112233 ryan 445566 john 334455 jack john jay 4576654 this is also junk line (just a number)
I hope this gets your thinking moving in more of a "Perl direction". Have Fun.
As a comment, I encourage you to space the code out, using appropriate comments and sometimes just a blank line to separate "thought units". White space consumes no MIPs! But that and comments can be some of the most important "code" that you write!
|
|---|