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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |