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

I'm confused as to how to evaluate whether or not the value of a variable is between two numbers OR is equal to some string. I can evaluate either condition, but not both. Here's what I've got, so far:
my $validExp = 0; while (!$validExp) { print "When would you like this account to expire? Enter N days \( +between 90 and 365\) or never\n"; chomp($expire = <>); if ($expire ge 90 && $expire le 365) { print "account will expire in: $expire days\n"; $validExp = 1; } elsif ($expire eq "never") { print "account will expire: $expire\n"; $validExp = 1; } else { print "Invalid entry. Enter N days \(between 90 and 365\) or n +ever\n"; } }

Replies are listed 'Best First'.
Re: Is "N" ge 90 && le 365 or does "N" = <string>?
by Abigail-II (Bishop) on Jan 29, 2004 at 17:35 UTC
    The alphabetic comparison operators are for alphabetic comparison, the the symbol operators are for numeric comparison - just opposite of what the shell does.

    Now, you might think that you can handle the situation like this:

    if ($expire >= 90 && $expire <= 365 || $expire eq "never")
    but there is a catch. If $expire is for instance "100 yellow ribbons", Perl will say hey, you are using $expire as a number, so I'll make it a number for you. Since it starts with 100, I'll pretent its value is 100.. This may, or may not be what you want. (With warnings on, Perl will issue a warning in this case, a warning you also get if $expire equal "never"). It's a more serious issue if the range you compare against includes 0, as a string that doesn't start with something that looks like a number will be considered to be 0 if used in numeric context.

    So, write your condition as:

    if ($expire =~ /^\d+$/ && $expire >= 90 && $expire <= 135 || $expire e +q "never")
    You might want to modify the first clause if fractional values are to be accepted as well.

    Abigail

      This is exactly what my confusion was. Thank you for your explanation! --S
Re: Is "N" ge 90 && le 365 or does "N" = <string>?
by Fletch (Bishop) on Jan 29, 2004 at 17:08 UTC

    You're confused about string comparison operators (ge) versus numeric comparison operators (>=). Read perldoc perlop.

Re: Is "N" ge 90 && le 365 or does "N" = <string>?
by mawe (Hermit) on Jan 29, 2004 at 17:18 UTC
    I think this will do it:
    ... if ($expire >= 90 && $expire <= 365) ...