"Perl for Perl Newbies" - Part 2References[ @array ] - a Dynamic Reference to an Array

10.3. [ @array ] - a Dynamic Reference to an Array

An array surrounded by square brackets ([ @array ]) returns a dynamic reference to an array. This reference does not affect other values directly, which is why it is called dynamic.

We have already encountered such dynamic array references in the Hanoi example. But their use is not limited to what we've seen there. Since a reference to an array is a scalar, it can serve as a hash value and therefore serve as an object member. (as will be seen later in the series).

In this example, a function is given two arrays, and returns an array that is the element-wise sum of both of them:

use strict;
use warnings;

sub vector_sum
{
    my $v1_ref = shift;
    my $v2_ref = shift;

    my @ret;

    my @v1 = @{$v1_ref};
    my @v2 = @{$v2_ref};

    if (scalar(@v1) != scalar(@v2))
    {
        return undef;
    }
    for(my $i=0;$i<scalar(@v1);$i++)
    {
        push @ret, ($v1[$i] + $v2[$i]);
    }

    return [ @ret ];
}

my $ret = vector_sum(
    [ 5, 9, 24, 30 ],
    [ 8, 2, 10, 20 ]
);

print join(", ", @{$ret}), "\n";

Note

The fundamental difference between using \@myarray on an existing variable named @myarray to using [ @myarray ] is this: the latter form creates a dynamic copy of @myarray and if this copy changes, @myarray will not change with it. On the other hand, changes made to a reference generated by backslash, will affect the original variable.

Note that if the members of @myarray are themselves references, then the second form will not make a deep copy of them. Thus, they can be modified too, even in the second form.


Written by Shlomi Fish