http://www.perlmonks.org?node_id=581151

Cristoforo has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks

I don't understand why the following code won't accept a value within the range specified. It dies even when values that should be valid are given. Thanks for any light you may shed on this

Chris

#!/usr/bin/perl use strict; use warnings; use Getopt::Std; my $usage = "Usage; $0 [-t x] where x is a time interval in minutes from 10 to 60. If no interval is given, defaults to 1 hour (60 min).\n"; my %opts; getopts ('t:',\%opts); my $interval = $opts{t} || 60; die $usage unless $interval == 10 .. $interval == 60;

Update:

Thank you for your helpful answers. I have read perlop (probably not closely enough :-) ). I was looking at some old code snippets i kept around and thought that one of them did what I was first attempting

for my $i (1 .. 15) { if(my $cnt = $i==5 ... $i==10) { print "$i - $cnt\n"; } } prints C:\perlp>range_op.pl 5 - 1 6 - 2 7 - 3 8 - 4 9 - 5 10 - 6E0

I think in this example it becomes true when $==5 and then becomes false when $i==10. Just some fuzzy thinking on my part. I guess neniro's example is the one that will work for me.

Thanks again

Chris

Replies are listed 'Best First'.
Re: Range operator doesn't seem to work
by neniro (Priest) on Oct 29, 2006 at 19:04 UTC
    die $usage if ($interval < 10 or $interval > 60);
Re: Range operator doesn't seem to work
by gaal (Parson) on Oct 29, 2006 at 18:49 UTC
    In Perl 5, the .. operator in scalar context is a "flip flop" which is false until its left operand of it evaluates as true, and then is true in subsequent checks until the right operand is true (and then potentially true and false over and over again).

    So you were checking something like "As long as $interval is 10 and until it is 60", not that it is between 10 and 60. If you read about this useful operator in perlop you'll see that as a special case, when an operand is just a number, that's taken as a line number in the input. Either way, this doesn't have much to do with what you were attempting!

    Incidentally, Perl 6 allows you to write:

    die $usage unless $interval ~~ 10 .. 60; # note use of "smart +match" ~~ operator
Re: Range operator doesn't seem to work
by mickeyn (Priest) on Oct 29, 2006 at 18:48 UTC
    you should read perldoc perlop.

    the range operator probably does not do what you meant.

    HTH,
    Mickey