in reply to Inplace file edit mark II
How can I use Perl's "-i" option from within a program? "-i" sets the value of Perl's $^I variable, which in turn affec +ts the behavior of "<>"; see perlrun for more details. By modifying +the appropriate variables directly, you can get the same behavior within a larger program +. For example: # ... { local($^I, @ARGV) = ('.orig', glob("*.c")); while (<>) { if ($. == 1) { print "This line should appear at the top of eac +h file\n"; } s/\b(p)earl\b/${1}erl/i; # Correct typos, pre +serving case print; close ARGV if eof; # Reset $. } } # $^I and @ARGV return to their old values here This block modifies all the ".c" files in the current directory +, leaving a backup of the original data from each file in a new ".c.o +rig" file.
That is one approach, using <> by setting @ARGV. If you simply wish to work on another filehandle, look at the first question in perlfaq5 ("How do I flush/unbuffer an output filehandle? Why must I do this?"), where it states how to set per-filehandle variables (like $| and our desired variable $^I):
or if you wish to keep the new OUTPUT_HANDLE selected, simply select( OUTPUT_HANDLE ); $^I = '.orig'; Good luck! Update: Trying to actually answer the question.# Long, understandable version $old_fh = select(OUTPUT_HANDLE); $^I = '.orig'; select($old_fh); # Short version $^I = '.orig', select $_ for select OUTPUT_HANDLE;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Inplace file edit mark II
by GrandFather (Saint) on Jun 10, 2005 at 02:19 UTC |