Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re^2: octal number mysteriously changes after pass to subroutine

by Anonymous Monk
on Feb 01, 2023 at 19:46 UTC ( [id://11150075]=note: print w/replies, xml ) Need Help??


in reply to Re: octal number mysteriously changes after pass to subroutine
in thread octal number mysteriously changes after pass to subroutine

Thank you pryrt++

Here's another conundrum, why don't these behave the same:

perl -le '$n=0666; print $n'
438
perl -le '$n=shift; print $n' 0666
0666

Replies are listed 'Best First'.
Re^3: octal number mysteriously changes after pass to subroutine
by Corion (Patriarch) on Feb 01, 2023 at 19:48 UTC

    The one embedded in the source code is an octal number string literal to Perl. The other is a string to Perl, as it comes from @ARGV.

    If you want to treat incoming parameters as octal, see the oct function.

    Updated: s/number string/number literal/, suggested by LanX

Re^3: octal number mysteriously changes after pass to subroutine
by LanX (Saint) on Feb 02, 2023 at 00:55 UTC
    There are fundamental things in Perl, which might be confusing here

    1. a scalar variable can be a number or a string (or a reference ...)
    2. There are various literal notations in code
    3. literals like "txt" , 'txt' , q(txt) , ... will produce the same string txt
    4. literals like 016 , 0xE , 14 will produce the same number (well integer) 14
    5. a string might look like a literal notation of a number like "016" , but literal notation inside strings will not be interpreted
    6. an implicit string to number conversion will always be decimal, hence "016" + 3  == 19 not 17
    7. if you want another base, you need to convert the string explicitly by yourself
    8. one (dangerous) way is eval("016") == 14

    I hope it's clearer now.

    Cheers Rolf
    (addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
    Wikisyntax for the Monastery

Re^3: octal number mysteriously changes after pass to subroutine
by ikegami (Patriarch) on Feb 01, 2023 at 21:01 UTC

    Arguments are received as strings. The second is equivalent to

    perl -le '$n="0666"; print $n'
    and
    perl -le '$n=q(0666); print $n'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11150075]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2024-04-20 02:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found