in reply to Read and skip a line

Look at the functions for array manipulation: shift, pop, unshift and push - and splice.

You might want to iterate over the file while reading, instead of loading it into memory as a whole. Then the next keyword could be of interest to you:

my $first; while (<FILE>) { s/\s+$//; # strip newline and whitespace from end of line if( ! $first++) { print "The first line is '$_'\n"; next; }; print "Some other line is '$_'\n"; };

Replies are listed 'Best First'.
Re^2: Read and skip a line
by DaveMonk (Acolyte) on Apr 15, 2012 at 20:41 UTC
    Hmm.. I couldn't get it to work, so I did a bit more on what I had, but now it prints out a certain line, by how many lines there are in total
    #!/usr/bin/perl -w use strict; open (FILE, '<', shift); my @file = <FILE>; close (FILE); my $first = shift @file; foreach my $line (@file) { chomp $line; for (my $i = 1; $i <= $first; $i++) { print "Line $i: $line\n"; } }

    Original content restored above by GrandFather

    Ok sweet, I've got it to work your way, and I used the next and shift functions instead of giving a value through $line[0] :D
      Most perl programmers would do this the way Corion indicated.

      Your logic is incorrect - here is a version using a "for loop" that you seem to want - , but coded in a more idomatic manner:

      use strict; use warnings; my $filename = shift; open my $file, "<", Filename or die "Cannot open $filename: $!"; chomp (my $lastrecord = <$file>); # Reads in the first record for (my $rec = 1; $rec <= $lastrecord and not eof($file); $rec++) { chomp(my $line = <$file>); print "Line $rec: $line\n"; };
      There is a small,subtle potential problem inherent in the code above - not corrected in order to maintain simplicity : the $line read in may be empty at EOF.

      UPDATE:Please do not delete code/comments after posting them - it makes responses like mine look out of context. It also prevents others from learning because context disappears.

                   All great truths begin as blasphemies.
                         ― George Bernard Shaw, writer, Nobel laureate (1856-1950)