0

In exploring an alternative answer to sarathi's current file line number question, I wrote this one-liner with the expectation that it would print the first line of all files provided:

$ perl -ne 'print "$ARGV : $_" if __LINE__ == 1;' *txt

This did not work as expected; all lines were printed.

Running the one-liner through -MO=Deparse shows that the conditional is not present. I assume this is because it has been constant-folded at compile time:

$  perl -MO=Deparse -ne 'print "$ARGV : $_" if __LINE__ == 1;' *txt
LINE: while (defined($_ = <ARGV>)) {
    print "$ARGV : $_";
}
-e syntax OK

But why?

Run under Perl 5.8.8.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Zaid
  • 36,680
  • 16
  • 86
  • 155

2 Answers2

5

__LINE__ corresponds to the line number in the Perl source, not in the input file.

choroba
  • 231,213
  • 25
  • 204
  • 289
  • 1
    I'm enjoying my 'Aha!' moment here. Should have read [`perldata`](http://perldoc.perl.org/perldata.html#Special-Literals) more carefully... – Zaid Sep 12 '12 at 10:36
4

__LINE__ is the source line number i.e., the program line number. $. will give you the input file line number.

if you want to print all the first lines of all the files then you can try this:

perl -lne '$.=0 if eof;print $_ if ($.==1)' *.txt
Vijay
  • 65,327
  • 90
  • 227
  • 319
  • Yup! What muddled me up was the use of current file name and your problem's context – Zaid Sep 12 '12 at 10:42