Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

flip-flop interpolation

by Anonymous Monk
on May 13, 2015 at 09:53 UTC ( #1126534=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

print if 2 .. 4 # works print if $i .. $j # doesn't work # how to make second to work?

Replies are listed 'Best First'.
Re: flip-flop interpolation
by choroba (Bishop) on May 13, 2015 at 10:02 UTC
    Range Operators says:
    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, if you're not using constants, you have to do the comparison yourself:
    print if ($. == $i) .. ($. == $j); # The parentheses are optional.
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Thank you.
      And can't I say to Perl to use my $i and $j as constants?

        That is like asking to draw a red line using green ink :)

        The way to do it is to use the green ink to define a universe containing hardcoded red lines:

        #untested, and quite silly eval "print $_ if $i .. $j;";

        You could use the constant pragma but it is not really saving you anything.

        $ seq 1 6 > lines $ cat lines 1 2 3 4 5 6 $ perl -ne ' > use constant { I => 3, J => 5 }; > print if I .. J;' lines 3 4 5 $

        I hope this is of interest.

        Cheers,

        JohnGG

Re: flip-flop interpolation
by Anonymous Monk on May 13, 2015 at 10:25 UTC
Re: flip-flop interpolation
by GotToBTru (Prior) on May 13, 2015 at 18:25 UTC
    $i = 2; $j = 4; print "$_\n" for ($i..$j);

    Output:

    2 3 4

    Update: I missed what was obvious to choroba. Not so much a flip-flop as a filter:

    # show lines 2 thru 4 while (<>) { print if 2..4 } # this will print every line $i = 2; $j = 4; while (<>) { print if $i..$j }
    Dum Spiro Spero

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1126534]
Approved by Ratazong
help
Chatterbox?
[karlgoethebier]: ..the last hippies. They still perform. At least the survivors...
[Discipulus]: not survived
[Discipulus]: has pm some danish monk?
[Discipulus]: erix the problem was not rain in the brain.. ;=)
[erix]: I'll think about that for a bit; I'll figure it out
[erix]: (damn Discipulus for speaking in IQ tests :P )

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (10)
As of 2017-11-17 20:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:













    Results (272 votes). Check out past polls.

    Notices?