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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.