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.

Answers


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


Need Your Help

C Binary search tree insert not printing

c search insert binary-search-tree

I have the following binary search tree code:

Fancybox random display of images

javascript jquery random fancybox fancybox-2

I'm using Fancybox v2.0.5 with a group of images and would like to display the entire group of images in random order. I've tried a variety of jQuery shuffle scripts, but they don't seem to integrate

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.