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

Guys,
Here are 2 code snippets for array of array refs:
@t_arr2 = ("one", "two", "three"); push(@t_arr, \@t_arr2); @t_arr2 = ("four", "five", "six"); push(@t_arr, \@t_arr2); for $str1 ( @t_arr ) { print "$str1->[0]\n"; print "$str1->[1]\n"; print "$str1->[2]\n"; }
and
@t_arr2 = ("one", "two", "three"); push(@t_arr, [@t_arr2]); @t_arr2 = ("four", "five", "six"); push(@t_arr, [@t_arr2]); for $str1 ( @t_arr ) { print "$str1->[0]\n"; print "$str1->[1]\n"; print "$str1->[2]\n"; }

The first gives me :

four five six four five six
and the 2nd gives me
one two three four five six
The 2nd is the answer I want, but I don't understand the difference between taking an array ref \@arr and taking an array ref
[@array]
??
Cheers
Chris
PS you can assume the usual invocations
#!/usr/bin/perl -w use strict;
plus declarations

Replies are listed 'Best First'.
Re: Array of arrays & references
by xdg (Monsignor) on Mar 15, 2006 at 00:09 UTC

    The backslash gives a reference to an existing array. The brackets create a new anonymous array reference that is a copy of what is between the brackets.

    In your first example, you have two references to the same array. In the second example, you have two references to two different arrays.

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Re: Array of arrays & references
by rafl (Friar) on Mar 15, 2006 at 00:08 UTC

    In the first snippet you actually push a reference to @t_arr2 into @t_arr. If you modify @t_arr2 later those changes will also propagate to all places where @t_arr2 is referenced, such as @t_arr. That's the nature of references.

    The second snippet pushes an anonymous array reference, which is a copy of @t_arr2, into @t_arr. Therefor @t_arr doesn't get changed when changing @t_arr2

    Cheers, Flo

Re: Array of arrays & references
by chrism01 (Friar) on Mar 15, 2006 at 00:23 UTC
    OK, thx guys.
    I do actually grok references (generally), but the bits of docs I was reading didn't clearly state the difference, ie that the 2nd method creates a ref to a new copy(!) of the array, as opposed to 1st method which creates a ref to the orig array..., they just talked about a ref to the array.
    I suppose the results imply that, but it's nice to have it stated explicitly. It might have been a fortunate side-effect of something else I was missing.
    Cheers
    Chris