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

Hello monks,

can someone explain to me why this bit of code works and also if it is legal to code like this:

my @array_rev=(); @{$array_rev[1]}=(1,2,3); print "@{$array_rev[1]}";

This code prints 1 2 3. But I don't understand how the second line can work since the array is uninitialized but @{} expects some valid reference!

Thank you :)

Replies are listed 'Best First'.
Re: Accessing uninitialized arrays. Black magic
by Athanasius (Archbishop) on May 27, 2013 at 02:32 UTC
Re: Accessing uninitialized arrays. Black magic
by 2teez (Vicar) on May 27, 2013 at 04:28 UTC

    Hi Anonymous Monk,
    Just a reminder, that the array @array_rev has undef as it's first element, since array index start from "0". So, what you are doing with this @{$array_rev[1]}=(1,2,3); is to assign an array reference to the second element of the array @array_rev.
    Using Data::Dumper like so can give some insight:

    use Data::Dumper; my @array_rev; @{$array_rev[1]}=(1,2,3); print Dumper \@array_rev; __END__ $VAR1 = [ undef, [ 1, 2, 3 ] ];

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me