Hello monks. I was using perl to translate files from one format to another with something like the following: perl -p translation.pl file.in > file.out when I got lazy and decided that I should be able to just pass a list of input files, and let perl append .out (or replace the extension) to create an output file for each input file.

There are obviously more than one way to do it and I settled for:

for my $filename (@ARGV) { open my $input, '<', $filename or die "Couldn't open $filename: $!"; open my $output, '>', $filename.'.new' or die "Couldn't open $filena +me: $!"; while (<$input>) { say $output translate($_); } }

Now I'm wondering, is there some simpler way to do it? This looks like a pretty common task, and it is very close to what -i does, except the two files are swapped: I want the output in the file with the added extension and the original unchanged. There doesn't seem to be an option for it, so do you know of some hack (bring out your secret operators, I'm asking out of curiosity so I want even the bad answers :D ) or some module that would let me write my code without having to write the explicit while(<>) loop on the data?

NB: yup I already just asked that in the CB and got some answers. Like choroba's proposition to call the translation.pl file inside a shell loop to handle the output files.

Edit: perl -pE "open STDOUT, '>>', qq<$ARGV.txt>; s/(.*)/\U$1/;" FILES works once :P (inspired by choroba's proposition)


In reply to One to one file output idiom by Eily

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.