in reply to Re: Inserting a line in the middle of a text
in thread Inserting a line in the middle of a text

That seems like a contortion to avoid opening an input filehandle and a separate output filehandle.

use strict; use warnings; my $filename = "inputfile.txt"; my $outputfile = $filename . "out"; my( $infh, $outfh ); open( $infh, '<', $filename ) or die $!; open( $outfh, '>', $outputfile ) or die $!; while( my $line = <$infh> ) { if( $line =~ /\bWilliam\b/i ) { print $outfh "Nick\n"; } print $line; } close $infh or die $!; close $outfh or die $!; rename $outputfile, $filename or die $!;

This is pretty close to what the -i commandline switch does for Perl one liners, with the exception of the "-i.bak" behavior, which could easily be implemented here too.

This whole thing could be written as a one liner, by the way:

perl -pi.bak -e "/\bWilliam\b/i && print qq/Nick\n/;" filename.txt

Obviously I forgot the names you're searching on, but the principle works.


Dave

Replies are listed 'Best First'.
Re^3: Inserting a line in the middle of a text
by ikegami (Patriarch) on Jan 20, 2009 at 17:34 UTC

    There are some advantages to working in-place over creating a temporary file:

    • File permission and ownership is maintained.
    • Using a temporary file requires more permissions.
    • Using a temporary file may complicate the locking system required.
    • Working in-place can be faster in some situations.

    This is pretty close to what the -i commandline switch does for Perl one liners

    -i is closer to

    open(my $fh_in, '<', $qfn); unlink($qfn); open(my $fh_out, '>', $qfn); ...

    for now.