http://www.perlmonks.org?node_id=81186


in reply to modifying and overwriting a file

In the perl man-pages "modifying and overwriting a file" is called inplace-editing. Perl has special provisions for that.

chipmonk explained the usage on the command line in his previous article. If you don't want to use the command line you can use some built-in variables. Quoting from perlvar:

$INPLACE_EDIT
$^I

The current value of the inplace-edit extension. Use undef to disable inplace editing. (Mnemonic: value of -i switch.)

@ARGV

The array @ARGV contains the command line arguments intended for the script....

$ARGV

contains the name of the current file when reading from <>.

to inplace-edit several file, you push them onto @ARGV, set $^I if you want to have backups of the files, and then just read from <> and write to STDOUT like so:

@ARGV = ('firstfile.txt', 'secondfile.txt'); $^I = '.bak'; while (<>){ # print STDERR "working on file $ARGV\n"; chomp $_; print $_, "_\n"; }

This creates backups of the original files as a side effect (the backups are called 'firstfile.txt.bak' and 'secondfile.txt.bak')

BEWARE! If you run the program again, you add another underscore, and loose the backup. Avoiding that is left as an exercise to the reader :-)

--
Brigitte    'I never met a chocolate I didnt like'    Jellinek
http://www.horus.com/~bjelli/         http://perlwelt.horus.at