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

Hi to everyone, i'd like to print a determinate line number
I'd like to know if there is a metod to print a determinate line number, for example:
#something is omitted $line_number= $.; if ( $line_number == 5) { print "The $line_number is: ". #here i have to print the fifth line +of the text file }
Thanx, B/R

Replies are listed 'Best First'.
Re: print a determinate line number
by jakobi (Pilgrim) on Oct 06, 2009 at 10:31 UTC

    check the ***magic*** $., man perlvar

    HANDLE->input_line_number(EXPR) $INPUT_LINE_NUMBER $NR $. Current line number for the ***last filehandle*** acces +sed.

    Actually it's a bit more magic than you might like, in which case doing it yourself might be safer when using multiple input handles in a program.

      check the ***magic*** $.

      Looks like the OP is already using $.  So I can only guess that the question is how to directly jump to a certain line in a file without going through the content before that line... in which case my reply would be that this could only be done if the lines all have the same length...  Kinda speculative, of course.

        That would require e.g. seek(), which can be way faster. If the data format allows to use it.

        Maybe that's idiom the opener missed (line-by-line reading of input)

        while(<>){ # <>: used handle is STDIN print if $.==5; # so $. is that handle's line number }

        or do it yourself in say $i

        my $file="/etc/hosts"; my $i=0; # let's use 1-based numbers open(FH,"<",$FILE) or die "dying on $FILE"; while(<FH>){ $i++; print "$i: $_" if $i == 5; }
Re: print a determinate line number
by arun_kom (Monk) on Oct 06, 2009 at 10:57 UTC

    sorry if i think too simple, but did you mean you need to print whatever is on the 5th line ... $_ contains it ;)

    if( $line_number == 5 ){ print "Line $line_number contains this text:\n", $_, "\n"; }
      Now I explain better my problem, I have to compare the text lines like this: the first with the second, the second with the third and so on and if the following line is different from the previous i have to print it.
        if the following line is different from the previous i have to print it

        For that, you'd have to keep the previous line:

        my $prev; while (<>) { print if defined($prev) and $_ ne $prev; $prev = $_; # update $prev }

        (The defined check would skip the first line, as there isn't really one previous to it...)

        ah i see it now ;) ... something like this then.
        use strict; use warnings; my $previous_line; while(<DATA>){ chomp; if($.==1){ $previous_line = $_; next; } if($_ eq $previous_line){ print "Line $. : $_\n"; } $previous_line = $_; } __DATA__ a b b c c c d
        UPDATE:

        Sorry the code above prints the duplicated lines, which is the opposite of what you wanted. i see that almut already has an elegant solution for you.