Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: keyword query

by erikharrison (Deacon)
on May 06, 2002 at 22:46 UTC ( [id://164478]=note: print w/replies, xml ) Need Help??


in reply to keyword query

Not bad really. You're very close, good for a beginner. Let's go through it.

#usage: ./getfone.pl output use strict; open(NL, "namelist.txt) || die $!; open(PB, "phonebook.txt") || die $!; open(OUT,">$ARGV[0].txt") || die $!;

So far so good. Especially good seeing the die. It might be useful to add some useful info of your own to the die's though, and as long as you are using strict you might as well use warnings.

while(1) {

Alright, an infinite loop. These are rarely useful, outside of event handlers. Rethink this.

my @phonelisting = <PB>; chomp(@phonelisting); my @name = <NL>; chomp(@name);

Alright, you're reading the files into arrays and chomping them. Fair enough. However, you're doing this inside a loop. Consider - the while loop starts, every line of both files are read into the two arrays. Why loop again. Even if your loop is necessary, why read the files in at the begining of each iteration?

my @phonesearch = grep @name, @phonelisting;

This is your real problem. grep doesn't quite work this way. grep take a block and a list. It iterates through the list, executing the block for each member of the list setting the $_ to the list member, then returns a list of every member which got the block to return true. This is where you're having problems.

print OUT "@phonesearch\n"; last if eof;
Alright, the print is fine assuming that the grep went right (which it didn't). The eof however is less good. It does what you want it to - breaks the loop if we've reached the end of NL - which we always will, cause we read in the whole file to the array @name. Effectively, the while allways iterates once. Why not just drop the while?

Also note that your otherwise well indented code, was improperly indented here. Line the print and the last up with the my in the previous line, for clarities sake.

close (NL); close (PB); close (OUT)

And no problem here. You close the files (which perl would do for you, but it's nice that you did it anyway), however, you (validly) drop the semicolon after the last close. Now, while the semicolon isn't required it's considered good form, in case you add a line latter, and then wonder about the new slew of syntax errors.

Cheers,
Erik

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://164478]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2024-03-28 14:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found