Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

RE: Can't open file within subroutine

by chromatic (Archbishop)
on Jun 14, 2000 at 23:45 UTC ( [id://18165]=note: print w/replies, xml ) Need Help??


in reply to Can't open file within subroutine

I'd do it this way, for a variety of reasons. The subroutine nested within the block bothers me, and I think there's a better way to handle the file reading:
#!/usr/bin/perl -w use strict; local *EXA; local *INFO; opendir (EXA, "/export/home/cad/data/products") || die "no dir?: $!"; foreach my $name(sort readdir (EXA)) { print "$name\n"; open(INFO, "/export/home/cad/data/products/$name/source/$name.bom" +) || die "no dir: $!"; while (my $line = <INFO>) { $line=~tr/(//d; #Cut out all the exa garbage $line=~ s/COMP//; $line=~ s/BOARDPLACEMENT_BOM brd//; print "\n $line "; } close(INFO) ; print "\n ------------------------ \n"; } closedir(EXA);
Not only is this a little cleaner, and it gets rid of the troublesome nested subroutine, it avoids reading a potentially large file into memory. If you're just going to iterate over each line later, why use an array? (Acceptible answer, "When you need to open and close the file as quickly as possible.")

Explanation of the local: I like declaring typeglobs, it's fun. If you're really particular, wrap the whole bit in a block, from before the local statements to after the close statement, and this can be part of a bigger program that might also have filehandles named EXA and INFO. You won't clobber them here.

Replies are listed 'Best First'.
RE: RE: Can't open file within subroutine
by jlp (Friar) on Jun 15, 2000 at 15:26 UTC
    Any particular reason for local()-izing the directory handle? And the filehandle needs to be localized within the foreach.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (2)
As of 2024-04-25 06:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found