2

I noticed this while looking at another question...

If I have a script like this:

while (<>) {
  print if 5 .. undef;
}

It skips lines 1..4 then prints the rest of the file. However if I try this:

my $start_line = 5;
while (<>) {
  print if $start_line .. undef;
}

It prints from line 1. Can anyone explain why?

Actually I'm not even sure why the first one works.

Hmmm looking further into this I found that this works:

my $start = 5;
while (<>) {
  print if $. ==  $start .. undef;
}

So the first version magically uses $. which is the line number. But I don't know why it fails with a variable.

Community
  • 1
  • 1
John C
  • 4,276
  • 2
  • 17
  • 28

1 Answers1

10

The use of a bare number in the flip-flop is treated as a test against the line count variable, $.. From perldoc perlop:

If either operand of scalar ".." is a constant expression, that operand is considered true if it is equal (==) to the current input line number (the $. variable).

So

print if 5 .. undef;

is "shorthand" for:

print if $. == 5 .. undef;

The same is not true for a scalar variable as it is not a constant expression. This is why it is not tested against $..

Zaid
  • 36,680
  • 16
  • 86
  • 155