develooper Front page | perl.perl5.porters | Postings from July 2008

shift->(@_) doesn't do the same as &{+shift}

Thread Next
From:
Vincent Pit
Date:
July 11, 2008 01:54
Subject:
shift->(@_) doesn't do the same as &{+shift}
Message ID:
48771FC9.3020203@profvince.com
I was wondering if
 
    sub f { shift->(@_) }

should do the same as

    sub g { &{+shift} }

Currently, f passes all its argument, including the one that appears at 
first glance shifted ; while g first shifts the first element and then 
only passes those that remain. I don't know is this behaviour is wanted, 
but it seems a little unnatural to me.

The reason appears in the optree dump. f gets compiled as

9  <1> leavesub[1 ref] K/REFC,1 ->(end)
-     <@> lineseq KP ->9
1        <;> nextstate(main 1 -e:1) v ->2
8        <1> entersub[t5] KS/TARG,1 ->9
-           <1> ex-list K ->8
2              <0> pushmark s ->3
4              <1> rv2av[t4] lKM/1 ->5
3                 <#> gv[*_] s ->4
-              <1> ex-rv2cv K/1 ->-
7                 <1> shift sK/1 ->8
6                    <1> rv2av[t2] sKRM/1 ->7
5                       <#> gv[*_] s ->6

while g as :

7  <1> leavesub[1 ref] K/REFC,1 ->(end)
-     <@> lineseq KP ->7
1        <;> nextstate(main 2 -e:1) v ->2
6        <1> entersub[t3] K/TARG,1 ->7
-           <1> ex-list K ->6
2              <0> pushmark s ->3
-              <1> ex-rv2cv vK/1 ->-
-                 <@> scope sK ->-
-                    <0> ex-nextstate v ->3
5                    <1> shift sK/1 ->6
4                       <1> rv2av[t2] sKRM/1 ->5
3                          <#> gv[*_] s ->4

In the first case, @_'s elements are pushed on the stack before the 
shift happens, so the previous copy is passed to the code that's in $_[0].

This has no impact on the common syntax "shift->meth(@_)", because in 
this case the shift happens before the method is resolved.

Comments?

Vincent.

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