JohnnyLoo JohnnyLoo - 3 months ago 14
Perl Question

How does the range operator work with constants, like in `print if 2..4`?

Let's say I have a file called text.txt that has this

one
two
three
four
five


If I have this in a perl script

open($fh, '<', text.txt) or die "blah blah";
while(<$fh>){
print if 2..4;
}


it will print two, three and four. How is that if statement comparing $_ with the range 2..4 in the background? In other words, If I use a different variable like $line instead of $_, what would I have to write that if comparison?

while(my $line = <$fh>){
print if........... 2..4 ?????????
}


Thank you. I love Perl, but there are a few things that I can't understand how it does them in the background.

Answer

There is certain amount of magic between range operator and $. built-in variable, which is described in following sentence from perlop (emphasis mine):

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

Essentially, the $. is a number of processed line (starting by one), which is compared with range. You may obtain the same result using named variable simply as:

while (my $line = <$fh>) {
   print $line if 2..4;
}

or if your prefer to write full-fledged if statement, there is an equaivalent form:

while (my $line = <$fh>) {
    if (2..4) {
        print $line;
    }
}

The complete, self-contained solution may be written as:

#!/usr/bin/env perl

use strict;
use warnings;

while (my $line = <DATA>) {
    print $line if 2..4;
}

__DATA__
one
two
three
four
five

yielding output as:

two
three
four
Comments