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
2
  • 2
    isn't it possible to store the file handles in an array? Commented Jan 10, 2010 at 17:15
  • 1
    There's an entire chapter in Intermediate Perl about doing this. :) Commented Jan 10, 2010 at 23:17

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

2 Comments

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
print {$list_of_file_handles[4]} $data;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.