Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: references--hard vs anonymous operational weirdness

by hipowls (Curate)
on Mar 23, 2008 at 03:19 UTC ( #675720=note: print w/ replies, xml ) Need Help??


in reply to references--hard vs anonymous operational weirdness

When you have \@array you create a reference to an array. Every time through the loop it is a reference to the same array. On the other hand [@array] is an anonymous array constructor that does a shallow copy of @array and creates a reference to the new copy.


Comment on Re: references--hard vs anonymous operational weirdness
Select or Download Code
Re^2: references--hard vs anonymous operational weirdness
by Fletch (Chancellor) on Mar 23, 2008 at 03:23 UTC

    Only if @array was declared outside the loop.</nit>

    my @array; for my $tab ( @things ) { @array = frobnicate( $tab ); ## As you've seen, this leaves everything pointing at the same array $data{ $tab } = \@array; }

    Were @array declared inside the loop you'd get a fresh instance each time through.

    for my $tab ( @things ) { my @array = frobnicate( $tab ); $data{ $tab } = \@array; }

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      Quite right, I'd got caught by an optimization. I ran (adjusting code to your example)

      for my $tab ( 1 .. 3 ) { my @array = frobnicate($tab); printf "Array ref: %s\n", \@array; printf "Annoymous: %s\n", [@array]; } sub frobnicate { return ( 0 .. shift ); } __END__ Array ref: ARRAY(0x826a924) Annoymous: ARRAY(0x8183a54) Array ref: ARRAY(0x826a924) Annoymous: ARRAY(0x826d818) Array ref: ARRAY(0x826a924) Annoymous: ARRAY(0x82115f8)
      The same address even though @array is declared in the loop. The variable is being reused. Assigning \@array to something prevents the optimization.
      my %data; for my $tab ( 1 .. 3 ) { my @array = frobnicate($tab); printf "Array ref: %s\n", \@array; printf "Annoymous: %s\n", [@array]; $data{$tab} = \@array; } sub frobnicate { return ( 0 .. shift ); } __END__ Array ref: ARRAY(0x826a924) Annoymous: ARRAY(0x8183a54) Array ref: ARRAY(0x819f318) Annoymous: ARRAY(0x8183798) Array ref: ARRAY(0x826ade8) Annoymous: ARRAY(0x819f304)
      Something to bear in mind when benchmarking.

        Assigning \@array to something prevents the optimization.

        Which optimization is that? Can you show the (incorrect) code which triggers this optimization?

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (14)
As of 2014-07-30 13:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (233 votes), past polls