Reputation: 905
Is there any way in Perl to generate file handles programmatically?
I want to open ten files simultaneously and write to them by using file handle which consists of (CONST NAME + NUMBER). For example:
print const_name4 "data.."; #Then print the datat to file #4
Upvotes: 3
Views: 677
Reputation: 22560
With a bit of IO::File
and map you can also do this:
use IO::File;
my @files = map { IO::File->new( "file$_", 'w' ) } 0..9;
$files[2]->print( "writing to third file (file2)\n" );
Upvotes: 5
Reputation: 1209
You can stick filehandles straight into an uninitialised array slot.
my @handles;
for my $number (0 .. 9) {
open $handles[$number], '>', "data$number";
}
Don't forget that the syntax for printing to a handle in an array is slightly different:
print $handles[3] $data; # syntax error
print {$handles[3]} $data; # you need braces like this
Upvotes: 9
Reputation: 943537
These days you can assign file handles to scalars (rather than using expressions (as your example does)), so you can just create an array and fill it with those.
my @list_of_file_handles;
foreach my $filename (1..10) {
open my $fh, '>', '/path/to/' . $filename;
push $list_of_file_handles, $fh;
}
You can, of course, use variable variables instead, but they are a nasty approach and I've never seen a time when using an array or hash wasn't a better bet.
Upvotes: 3