in reply to Capture Contents AND Overwrite without Opening Twice?

Not sure if it will do exactly what you want, but I'm thinking that Tie::File might work. You open the file for read/write access when you tie the file to an array. Then using array manipulations, you can add/remove/modify the contents of the file. Then the file is closed when you untie the file.

  • Comment on Re: Capture Contents AND Overwrite without Opening Twice?

Replies are listed 'Best First'.
Re^2: Capture Contents AND Overwrite without Opening Twice?
by GotToBTru (Prior) on Oct 09, 2014 at 00:45 UTC

    To wit: test.pl

    use strict; use warnings; use Tie::File; my $infile = shift; tie my @lines, 'Tie::File', $infile; printf "File has %d lines\n",$#lines+1; print "$_\n" for @lines; # clobber file @lines = (); printf "\nFile has %d lines\n",$#lines+1; print "$_\n" for @lines; # insert replacement lines push @lines, "replacement line here"; push @lines, "another new line"; printf "\nFile has %d lines\n",$#lines+1; print "$_\n" for @lines; untie @lines;

    Let's run it.

    $ perl test.pl test.file File has 4 lines one two three four File has 0 lines File has 2 lines replacement line here another new line

    Verify that we have in fact changed the file:

    $ cat test.file replacement line here another new line $

    Updated for readability

    1 Peter 4:10