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