in reply to Re: Re: Array of arrays
in thread Array of arrays

You can find all the info you need at perlref and perllol. Here's a brief description, though.

When you have a reference to something, there are two ways you can dereference it. By dereference I mean "take the pointer to an object and return the object." You can prefix the reference with the data type indicator or use the dereference operator. For example:

my @array = ('cow', 'dog', 'cat'); my $ref_to_array = \@array; my ($first, $second) = @{$ref_to_array}[0,1]; # prefix my $third = $ref_to_array->[2]; # deref operator

This really comes in handy when you have four levels deep of referencing and you need something at the bottom. Typically, the deref operator (->) is optional between multiple levels of dereferencing. For example:

my @LoL = (); # empty array $LoL[0] = []; # ref to anonymous array $LoL[0]->[0] = []; # another ref to anonymous array # the hard way ${${$LoL[0]}[0]}[0] = 'Look, up in the sky!'; # the easy way $LoL[0]->[0]->[1] = 'It's a bird, it's a plane, it's...'; # the shortcut $LoL[0]->[0][2] = 'Superman!';

Now that you have more information than you needed or wanted... In this particular example, Perl "Does What You Mean." When you write $LoL[5][3] Perl recognizes that there's no way to rewrite that to mean anything but what you meant to do in the first place. =) So it just assumes the shortcut.

That's probably the worst example of anything I've ever given. Go read the perldocs! {g}

Replies are listed 'Best First'.
Re: Re: Re: Re: Array of arrays
by chipmunk (Parson) on Jan 22, 2001 at 20:00 UTC
    Those are good examples of using references. I have one correction and one addition.
     

        my $first = @{$ref_to_array}[0]; # prefix That should be: my $first = ${$ref_to_array}[0]; # prefix Just like with a regular array, you should use $ when accessing a single element, and save @ for when you want a slice.
     

    # the easy way $LoL[0]->[0]->[1] = 'It's a bird, it's a plane, it's...'; # the shortcut $LoL[0]->[0][2] = 'Superman!';
    To finish the abbreviation:
    # the full shortcut $LoL[0][0][2] = 'Superman!';