Question

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
Was it helpful?

Solution

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

OTHER TIPS

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" );

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top