You should use strict and warnings in your script. They help you in writing better code.

You can use the predefined array @ARGV. It contains all arguments given to the script.

With ./script.pl file1.txt file2.txt you should find the two file names inside @ARGV.

Then you can do your modifications foreach file...

#! /usr/bin/perl use strict; use warnings; FILE: for my $file ( @ARGV ) { # check if $file contains a file name if ( !-f $file ) { warn "Sorry, '$file' doesn't look like a file!\n"; next FILE; } # if we can't open the file for reading, warn user if ( !open(my $infh, '<', $file) ) { warn "Sorry, couldn't open $file: $!\n"; } # we could open the file for reading else { # so, let's try to open a temporary file for writing if ( !open( my $outfh, '>', $file.'.new' ) ) { # and warn user if it failed warn "Sorry, couldn't open $file.new for writing: $!\n"; } else { # we now have two filehandles: # one to read from and one to write to. # read linewise from input filehandle while ( my $line = <$infh> ) { # print (to output filehandle) original line and append a newl +ine print $outfh $line, "\n" or die "writing to $file.new failed: +$!\n"; } # writing should be done now; close filehandle close $outfh or die "closing $file.new failed: $!\n"; } # reading should be done now; close filehandle close $infh or die "closing $file failed: $!\n"; } }

code was hacked quickly and is not tested!

You can do this even in one line ;o)

perl -i.bak -pe '$_.="\n"' file1.txt file2.txt file...

this was quickly tested and worked so far ;o)

Updates:


In reply to Re: IO::Handles ... any good? by linuxer
in thread IO::Handles ... any good? by blowupp

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.