Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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:

$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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://81186]
help
Chatterbox?
[choroba]: #cbstream still down?
[erix]: yeah, annoying
[choroba]: last ambrus: 1 week ago :-(
[erix]: let's invade Hungary
[planetscape]: darn
[erix]: probably on holiday, the slacker
erix is reduced to use a BROWSER. (remember those?)
[Discipulus]: figuring.. i'm still just use the side pm chat..
[erix]: (all this while karls guitar gently weeps...)

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2017-06-22 21:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How many monitors do you use while coding?















    Results (530 votes). Check out past polls.