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
brian d foy
  • 129,424
  • 31
  • 207
  • 592
dan
  • 885
  • 2
  • 9
  • 18

3 Answers3

9

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
  • 1,189
  • 8
  • 8
5

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" );
AndyG
  • 39,700
  • 8
  • 109
  • 143
draegtun
  • 22,441
  • 5
  • 48
  • 71
3

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335