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

I was browsing trough the rules for Perl Golf, when I saw the following one-liner:

perl -wle 'print []+0'

On my macine, it returns 134531284, and indeed the page says: "You may assume that such an address will be > 100000 (At least one machine is known where the number is 156000) You may assume the address is a multiple of 4." So it has something to do with addresses of objects, but since I've never heard about this in the context of perl before, I hope that someone can clarify this for me.

Replies are listed 'Best First'.
Re: addresses of objects
by Fletch (Chancellor) on Aug 09, 2004 at 15:23 UTC

    It's documented in perldoc perlref.

    Using a reference as a number produces an integer representing its storage location in memory.
Re: addresses of objects
by davido (Cardinal) on Aug 09, 2004 at 15:41 UTC

    The -w switch seems to be unnecessary, and the -l switch seems only to assure that a newline is spit out at the end of the print. If you can do without that, and eliminate all unnecessary whitespace, you can save four more keystrokes:

    perl -e'print[]+0'

    The principle is this: [] creates an anonymous array reference. Evaluated in scalar context, it would appear as (for example) "ARRAY(0x155513c)." The "+0" operation causes the numeric value of the string "ARRAY(0x155513c)" to be added to zero, resulting in the non-numeric portion of "ARRAY(0x155513c)" being dropped. Finally, print automatically represents the hex number in base ten. The result (on my computer) is "22368572", which happens to be the base-10 version of the hex number "0x155513c".


    Dave

      I think you mean "string context", not "scalar context". Scalar context per se doesn't turn a reference to anything.

      And the numeric value of a string "ARRAY(0x155513c)" is zero:

      perl -e "$x = []; print qq{$x}+0"
      In the original case the reference is evaluated in numerical context, not first in string and then numerical. And in numerical context reference evaluates to the address.

      Jenda
      Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
         -- Rick Osborne

      The -w switch seems to be unnecessary, and the -l switch seems only to assure that a newline is spit out at the end of the print.
      just commenting on that:
      when i'm coding on commandline i always use -wle now. it's just automatically. without that i would have been bitten so often from a missed warning. and -l is just so convenient.
      also if i copy and paste commandline code from others i find it annoying if it doesn't contain -wl

        I understand the convenience issues with -l, and the helpful guidance of -w warnings. But the original question was prompted by a thread on Perl golf. And a golf solution that saves two keystrokes (wl) without breaking the results is... better golf. ;)


        Dave