views:

154

answers:

3

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
+3  A: 

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.

David Dorward
But if i want to write to the fifth file for example how i do it also you means push @list_of_file_handles, $fh; ?thanks
dan
print {$list_of_file_handles[4]} $data;
David Dorward
+9  A: 

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
Porculus
+4  A: 

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

/I3az/

draegtun