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

Re: How can I create an array of filehandles?

by CharlesClarkson (Curate)
on Jun 11, 2001 at 09:35 UTC ( [id://87404]=note: print w/replies, xml ) Need Help??


in reply to How can I create an array of filehandles?

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; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://87404]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (2)
As of 2024-04-20 04:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found