Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
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


Comment on Re: modifying and overwriting a file
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2014-12-18 02:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (41 votes), past polls