Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Naming file handles with variables?

by GrandFather (Cardinal)
on Apr 30, 2009 at 04:41 UTC ( #761039=note: print w/ replies, xml ) Need Help??


in reply to Naming file handles with variables?

You really don't want to be managing an unknown number of file handles 'retail'. Instead think of using a collection of handles. The easiest way is probably an array, although depending on the nature of the rest of the task a hash keyed by file name may be a better choice. Consider:

use strict; use warnings; my @fileNames = ('file1.txt', 'foo.txt', 'wibble.wav'); my @fileHandles; for my $filename (@fileNames) { open $fileHandles[@fileHandles], '<', $filename or die "Can't open + $filename: $!"; } while (@fileHandles) { for my $file (@fileHandles) { my $line = <$file>; if (! defined $line) { # Hit end of file close $file or die "File close failed: $!"; $file = undef; next; } # do something with $line } @fileHandles = grep {defined} @fileHandles; }

which opens a bunch of files then enters a loop that reads a line from each file in turn and does something with each line.


True laziness is hard work


Comment on Re: Naming file handles with variables?
Download Code
Re^2: Naming file handles with variables?
by QM (Vicar) on May 01, 2009 at 03:53 UTC
    Should that be [$filename] here?
    for my $filename (@fileNames) { open $fileHandles[$filename], '<', $filename or die "Can't open $f +ilename: $!";

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

      I don't thinks so. open $fileHandles[@fileHandles], ... 'creates' a new array element for the new file handle. You could instead:

      open my $newFileHandle, ...; push @fileHandles, $newFileHandle;

      to achieve the same effect.

      If fileHandles were a hash instead of an array then keying by the file name would be appropriate however.


      True laziness is hard work
        OIC. Scalar context giving the next index. Hadn't seen this before, but it's interesting.

        I don't think I would use this myself, as I don't know who would be maintaining my code. I'd prefer the alternative you gave for transparency. Doubly preferred, given the OP's apparent sophistication level.

        -QM
        --
        Quantum Mechanics: The dreams stuff is made of

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (12)
As of 2014-07-25 17:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (174 votes), past polls