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

Hello Respected Monks, I first want to beg your pardon, and let you know that I am a newbie at Perl. I am have been exposed to Perl for about 2 weeks, hence the following question. Let's assume that I have a delimited file as shown:

ABC 123 HELLO

23222 PERL MATLAB

BARCELONA ISTANBUL CAIRO

I want to add a new line to this file with the word data, but I also want the original first line to be the second line, second to be the third, third to be.....ect, and thus, the final processed file should be like this:

data

ABC 123 HELLO

23222 PERL MATLAB

BARCELONA ISTANBUL CAIRO

You get the point, right? Any help you can provide will come back at you as karma points, so please help this poor newbie out on a nice Friday morning.

Replies are listed 'Best First'.
Re: Add a Line to a Text File
by xanadol (Novice) on Aug 23, 2013 at 17:43 UTC
    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;

      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,