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

I hope someone can help me here, I need to compare the month entered by the user I.E. as a date say 08 for the month of august but I ran into a snag between 07 and 08 I can only get it to work as an 8 but I need it as 08 for file naming. if I use 08 I get an error for illegal octal but I dont on say 07 for July. I've tried ==, eq, '08' "08" and about everything else but I'm still stuck. Is this a bug? or can I get some help? thanks.... still learning
if ($month eq 07 || 7) { $monthStamp = "July"; print "$monthStamp"; } if ($month eq 08 || 8) { $monthStamp = "August"; print "$monthStamp"; }

Replies are listed 'Best First'.
Re: problem or bug?
by Masem (Monsignor) on Oct 11, 2001 at 23:03 UTC
    You probably want:
    if ( $month eq '07' || $month eq '7' ) { ... }
    While it would seem to be intuitive, perl cannot use a single ==/eq to compare many things at once, you have to do each separately.

    -----------------------------------------------------
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
    It's not what you know, but knowing how to find it if you don't know that's important

Re: problem or bug?
by dragonchild (Archbishop) on Oct 11, 2001 at 23:04 UTC
    if ($month + 0 == 7) { ... # Or, better would be ... @month_names = ( '', 'January', ... ); $monthStamp = $month_names[$month];

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      I think the '+ 0' trick to force a numeric value is unnecessary here. It looks like '==' already does that for you. (of course your second suggestion is better than either of these, but still...)
      #!/usr/bin/perl -wT use strict; my @vals = ('07','7',07,7,8); # eq tests for my $month (@vals) { print $month, $month eq 7 ? ' eq' : ' !eq', " 7\n"; } print "\n"; # == tests for my $month (@vals) { print $month, $month == 7 ? ' ==' : ' !==', " 7\n"; } print "\n"; =OUTPUT 07 !eq 7 7 eq 7 7 eq 7 7 eq 7 8 !eq 7 07 == 7 7 == 7 7 == 7 7 == 7 8 !== 7

      -Blake

      Thanks guys!! learn something new everyday! :)
Re: problem or bug?
by guidomortonski (Sexton) on Oct 12, 2001 at 02:52 UTC
    You're trying to evaluate $month as a string. Try

    if ($month == 7) { $monthStamp = "July"; print "$monthStamp"; }

    This should work regardless of whether $month contains a number 7 or a string "07".

    Guy