Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

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

Comment on Re: modifying and overwriting a file
Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://81186]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (9)
As of 2015-11-26 12:47 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (698 votes), past polls