Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: modifying and overwriting a file

by bjelli (Pilgrim)
on May 17, 2001 at 12:16 UTC ( #81186=note: print w/replies, xml ) Need Help??

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:


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


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


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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://81186]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2017-05-25 00:45 GMT
Find Nodes?
    Voting Booth?