I am trying to understand in Perl the difference between a normal array reference \@array and [@array].
Covered in the following article, http://perl-begin.org/tutorials/perl-for-newbies/part2/, it says
"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. "
The last sentence above where it says the reference does not affect other values directly isn't clear to me, what other values are they refering to?  A few websites copied and paste the same explanation.  Can someone provide a better explanation that highlight the differences?
Here is an example they provided:
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";
However, in the example given above, if I change the return [ @ret ]; to \@ret, the program returns the same result, so I am not sure how this serves as an example to illustrate dynamic reference.
Thanks.
I question that tutorial. When the perl docs use the term "dynamic", they are almost always referring to variable scope. You won't find consideration of a "dynamic arrayref" in perlref nor perlreftut.
That said:
\@array   # reference to @array
[@array]  # reference to an unnamed *copy* of @array
Consider what happens when we take a reference to, or a reference to a copy of, @ARGV:
$ perl -E '$a = \@ARGV; $a->[0] = "FOO"; say for @ARGV' blah blah
FOO
blah
$ perl -E '$a = [@ARGV]; $a->[0] = "FOO"; say for @ARGV' blah blah
blah
blah
                        I am trying to understand in Perl the difference between a normal array reference
\@arrayand[@array].
They're both exactly the same kind of references; they just produce references to different arrays.
[ ... ]
is basically the same thing as
do { my @anon = (...); \@anon }
So
my @abc = qw( a b c );
my $ref1 = \@abc;
my $ref2 = [ @abc ];
say @$ref1, @$ref2;  # abcabc
@abc = qw( d e f );
say @$ref1, @$ref2;  # defabc
"This reference does not affect other values directly, which is why it is called dynamic. "
It's not called "dynamic", and that's not a definition of dynamic I've ever encountered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With