Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re: Naming file handles with variables?

by GrandFather (Sage)
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

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: $!";

    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.

        Quantum Mechanics: The dreams stuff is made of

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (11)
As of 2016-09-27 13:05 GMT
Find Nodes?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:

    Results (503 votes). Check out past polls.