Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: references--hard vs anonymous operational weirdness

by hipowls (Curate)
on Mar 23, 2008 at 03:19 UTC ( [id://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.

Replies are listed 'Best First'.
Re^2: references--hard vs anonymous operational weirdness
by Fletch (Bishop) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://675720]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2024-03-29 13:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found