Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Answer: How can I create an array of filehandles?

( #87404=categorized answer: print w/ replies, xml ) Need Help??

Q&A > files > How can I create an array of filehandles? contributed by CharlesClarkson

As of Perl 5.6.0 file handles can be autovivified. So it is possible to open a file like this:

open my $fh, '>', $file_name or die "Cannot open $file_name: $!";

This allows us to refer to the filehandle as $fh. The following sub returns a hash keyed to the file names:

my %handles = get_write_handles(qw/col1.txt col2.txt col3.txt/); sub get_write_handles { my @file_names = @_; my %file_handles; foreach (@file_names) { open my $fh, '>', $_ or next; $file_handles{$_} = $fh; } return %file_handles; }

Note that files that cannot be opened are not defined in the hash. Now the files can be referred to from %handles:

print { $handles{'in.txt'} } "something\n";

or:

foreach (values %handles) { print $_ "something\n"; }

To return an array we need to decide what happens if a file can't be opened. This sub dies:

sub get_read_handles { my @file_names = @_; my @file_handles; foreach (@file_names) { open my $fh, '<', $_ or die "Yikes $_: $!"; push @file_handles, $fh; } return @file_handles; }

While this will return undef for failed opens:

sub get_append_handles { my @file_names = @_; my @file_handles; foreach (@file_names) { if (open my $fh, '>>', $_) { push @file_handles, $fh; } else { push @file_handles, undef; } } return @file_handles; }

Comment on Answer: How can I create an array of filehandles?
Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (9)
As of 2014-12-27 19:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls