The snippet doesn't compress nicely. Now, if you had more repetition, we might be able to do something. If this is just a sample of your code and you have more repetitiion in your real code, can you show it to us? I can't predict how this code would expand.
You could let Perl close the handles for you:
{ local *FH; open(FH, "< ${file}.txt") or die "Can't open ${file}. +txt: $!\n"; local *FH1; open(FH1, "> ${file}1.txt") or die "Can't create ${file +}1.txt: $!\n"; while(<FH>) { print FH1 $_; } }
or in newer versions of Perl:
{ open(my $fh, '<', "${file}.txt") or die "Can't open ${file}.txt: +$!\n"; open(my $fh1, '>', "${file}1.txt") or die "Can't create ${file}1.tx +t: $!\n"; while (<$fh>) { print $fh1 $_; } }
But here is the answer to the question you asked. As I've said, it's not very useful.
my @file_data = ( [ undef, "${file}.txt", 'r' ], [ undef, "${file}1.txt", 'w' ], ); foreach (@file_data) { my $name = $_->[1]; my $mode = $_->[2]; $_->[0] = IO::File->new($name, $mode) or die("Can't " . ($mode eq 'w' ? 'create' : 'open') . " file $name +: $!\n"); } while (<$file_data[0][0]>) { print $file_data[1][0] $_; } close($_->[0]) foreach @file_data;
In reply to Re: Collapsing multiple file open/close
by ikegami
in thread Collapsing multiple file open/close
by ady
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |