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 | |
by GrandFather (Saint) on May 01, 2009 at 05:19 UTC | |
by QM (Parson) on May 01, 2009 at 14:09 UTC | |
by GrandFather (Saint) on May 01, 2009 at 22:15 UTC | |
by TGI (Parson) on May 03, 2009 at 15:28 UTC | |
|
In Section
Seekers of Perl Wisdom