Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

RE: Can't open file within subroutine

by chromatic (Archbishop)
on Jun 14, 2000 at 23:45 UTC ( #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/$" +) || 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?

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2023-11-28 10:23 GMT
Find Nodes?
    Voting Booth?

    No recent polls found