http://www.perlmonks.org?node_id=761039


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

Replies are listed 'Best First'.
Re^2: Naming file handles with variables?
by QM (Parson) 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