develooper Front page | perl.perl5.porters | Postings from May 2004

Re: ++(my $x = {}) [Was: Re: my $x->{foo} doesn't work]

Thread Previous | Thread Next
From:
Dan Kogai
Date:
May 21, 2004 13:09
Subject:
Re: ++(my $x = {}) [Was: Re: my $x->{foo} doesn't work]
Message ID:
C5459F0A-AB62-11D8-A4F1-000A95DBB50A@dan.co.jp
On May 22, 2004, at 04:25, Dan Kogai wrote:
> Hey, watch this!
>
>> % perl -le 'my $x=42; $x->[0]=3.14; print $x; print $x->[0]; print 
>> ref($x)'
>> 42
>> 3.14
>>
>> % perl -le 'my $x; $x->[0] = 3.14; print $x; print $x->[0]; print 
>> ref($x)'
>> ARRAY(0x801180)
>> 3.14
>> ARRAY
>
> See the difference?  The first one has 42 assigned a priori.  I have 
> duplicated this even on good old 5.00503, not to mention 5.8.4.

You can even nest....

> % perl -le 'my $x=42; $x->[0]=3.14; $x->[0][0]=6.022e23;' \
>   -e 'print "$x, $x->[0], $x->[0][0]"'
> 42, 3.14, 6.022e+23

And Devel::Peek says as follows.  Strangely ROK is nowhere to be seen.

> % perl -MDevel::Peek -le 'my $x=42; $x->[0]=3.14; 
> $x->[0][0]=6.022e23;' \
>   -e 'Dump $x;Dump $x->[0];Dump $x->[0][0]'
> SV = PVIV(0x801828) at 0x801234
>   REFCNT = 1
>   FLAGS = (PADBUSY,PADMY,IOK,POK,pIOK,pPOK)
>   IV = 42
>   PV = 0x401930 "42"\0
>   CUR = 2
>   LEN = 3
> SV = PVNV(0x811734) at 0x80a924
>   REFCNT = 1
>   FLAGS = (NOK,POK,pNOK,pPOK)
>   IV = 3
>   NV = 3.14
>   PV = 0x405280 "3.14"\0
>   CUR = 4
>   LEN = 35
> SV = NV(0x80e814) at 0x80f12c
>   REFCNT = 1
>   FLAGS = (NOK,pNOK)
>   NV = 6.022e+23

And Storable "respects" this undocumented feature....

> % perl -MStorable -le 'my $x=42; $x->[0]=3.14; $x->[0][0]=6.022e23;' \
>  -e 'store \$x=>"x"; my $y = retrieve "x"; print "$$y, $$y->[0], 
> $$y->[0][0]"'
> 42, 3.14, 6.022e+23

But this magic fades as you modify the value thereof....

> % perl -le 'my $x=42; $x->[0]=3.14; $x->[0][0]=6.022e23;' \
>   -e '$x=0; print "$x, $x->[0], $x->[0][0]"'
> 0, ,

But when you assign the same initial value it persists.... Maybe thanks 
to optimizer ?

> % perl -le 'my $x=42; $x->[0]=3.14; $x->[0][0]=6.022e23;' \
>   -e '$x=0; print "$x, $x->[0], $x->[0][0]"'
> 42, 3.14, 6.022e+23
> % perl -le 'my $x=42; $x->[0]=3.14; $x->[0][0]=6.022e23;' \
>   -e '$x+=0; print "$x, $x->[0], $x->[0][0]"'
> 42, 3.14, 6.022e+23
> % perl -le 'my $x=42; $x->[0]=3.14; $x->[0][0]=6.022e23;' \
>   -e '$x=2*3*7; print "$x, $x->[0], $x->[0][0]"'
> 42, 3.14, 6.022e+23

Dan the Zombie Hunter


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About