GrandFather has asked for the wisdom of the Perl Monks concerning the following question:

Ok, I have <> and $^I down pat for inplace file edit where files are passed on the command line. Is there a neat way of doing the same for <filehandle> rather than something like this:

my $SomeFile = "delme.txt"; open inFile, "<$SomeFile" or die "Can't open $SomeFile for input: $!"; open outFile, ">~$SomeFile" or die "Can't open ~$SomeFile for output: +$!"; print outFile while <inFile>; close inFile; close outFile; unlink "$SomeFile.bak"; rename $SomeFile, "$SomeFile.bak"; rename "~$SomeFile", $SomeFile;

Perl is Huffman encoded by design.

Replies are listed 'Best First'.
Re: Inplace file edit mark II
by kaif (Friar) on Jun 09, 2005 at 23:59 UTC
    Please see perlfaq5:
    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):

    # Long, understandable version $old_fh = select(OUTPUT_HANDLE); $^I = '.orig'; select($old_fh); # Short version $^I = '.orig', select $_ for select OUTPUT_HANDLE;
    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.

      Yep, that's what I wanted.

      You would think that in the few weeks I've been learning Perl that I wouldn't have time to forget stuff like that. I know I read it in the Camel or the Lama, but I hadn't used it and - poof - gone. :-(

      So the solution I was after is like this:

      local($^I, @ARGV) = ('.bak', 'delme.txt'); print outFile while <>;

      Perl is Huffman encoded by design.