in reply to Add a Line to a Text File

I got it, I hope someone also will be able to use this little silly script in their mundane tasks.
use strict; use warnings; my $infile = $ARGV[0] or die "$0 Usage:\n\t$0 <input file>\n\n"; open(my $fd , '<' , $infile) or die "$0 Error: Couldn't open $infile f +or reading: $!\n"; my $outfile = 'processedData.txt'; open(my $fh, '>', $outfile) or die "Could not open file '$outfile' $!" +; my $previous; print $fh "data\n"; while (<$fd>) { $previous = $_; print $fh $previous; } chomp($previous); close $fh;

Replies are listed 'Best First'.
Re^2: Add a Line to a Text File
by Athanasius (Archbishop) on Aug 24, 2013 at 04:04 UTC

    Hello xanadol, and welcome to the Monastery!

    Glad to see you found the solution. For the record, this is an FAQ: How do I change, delete, or insert a line in a file, or append to the beginning of a file?.

    Some observations on your code:

    • Great to see you useing strict and warnings!

    • The while loop can be written more idiomatically:

    • print $fh $_ while <$fd>;
    • chomping $previous after the while loop does nothing.

    If you want to prepend a line of text to an existing file in-place, you can use the core module Tie::File:

    use strict; use warnings; use Tie::File; my $file = $ARGV[0] or die "$0 Usage:\n\t$0 <file>\n\n" +; tie my @array, 'Tie::File', $file or die "Cannot tie file '$file': $! +"; unshift @array, 'data'; untie @array;

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,