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

Hi Perl Monks, I'd like to do some number comparisons using phone numbers, however as leading zero numbers are interpreted as octals, what's the best way to disable the interpretation of the leading zero as an octal in Perl?

Replies are listed 'Best First'.
Re: numbers with leading zeros
by ikegami (Patriarch) on Sep 24, 2008 at 06:36 UTC

    Numerical literal "010" is 8 decimal.

    >perl -wle"$x = 010; print $x; print $x == 10 ?1:0" 8 0

    String literal "'010'" is 10 decimal when treated as a number.

    >perl -wle"$x = '010'; print $x; print $x == 10 ?1:0" 010 1
Re: numbers with leading zeros
by Corion (Patriarch) on Sep 24, 2008 at 07:44 UTC
Re: numbers with leading zeros
by parv (Parson) on Sep 24, 2008 at 06:12 UTC

    Compare the phone number as strings?

    If you really want to compare a phone number as a number, add zero to the string representation of the number: $p = 0 + '0008'.

Re: numbers with leading zeros
by DrHyde (Prior) on Sep 24, 2008 at 10:15 UTC

    Oh goodie, an opportunity to plug my Number::Phone module! Although it doesn't have phone number comparison methods right now. Should I add them?

    Anyway, you can make perl compare your numbers correctly by making sure that you always treat them as strings. As you can see here, using string comparison operators Does The Right Thing with strings:

    $ perl -e 'print "01234" eq "01234"' 1 $ perl -e 'print "01234" eq "1234"'

    But using a numeric comparison Does The Wrong Thing:

    $ perl -e 'print "01234" == "1234"' 1
    The moment that you use any non-string operator on a variable, you can assume it will Do The Wrong Thing.