简体   繁体   中英

Perl Flip Flop operator and line numbers

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.

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 $. .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM