howa said:
i really don't understand their difference...i suppose they "should" be
the same
No. I suspect that your misunderstanding perhaps stems from thinking
that a list and an array are the same thing. They are not.
1. return \@arr; assign to $arr_ref
In this case, the function test() returns a reference to an array - a
variable that was created in the body of test(). test() is thus a
function that returns a scalar.
In this case test() returns a *list*, which contains the elements that
are stored in the array @arr, but it is not the same thing as @arr
assigh \test() to $arr_ref
Now you have a problem. test() returns a list. You apply \ to this list,
which returns a list of references to the elements of the list. Then you
assign this list to the scalar $array_ref. When you assign a list to a
scalar, you end up with the last element of the list (which is a
reference to the last thing in the list returned by test() ). Not what
you wanted at all.
Consider:
@foo = ('a', 'b', $bar);
$scalar1 = @foo; # $scalar1 = 3
$scalar2 = ('a', 'b', $bar); # $scalar2 = $bar
$scalar3 = \@foo; # $scalar3 holds a reference to the array @foo
$scalar4 = \('a', 'b', $bar); # $scalar4 holds a reference to $bar
Perhaps this SBCS will make it ever clearer:
----
#!/usr/bin/perl
use strict;
use warnings;
my @foo = ('a', 'fine', 'kettle', 'of', 'fish');
my ($x, $y, $z) = \('bib', 'bob', @foo);
my $q = \('bib', 'bob', @foo);
print $$x, ' ';
foreach my $element (@$z) {
print "$element ";
}
print "\n";
print $$y, ' ';
foreach my $element (@$q) {
print "$element ";
}
----
Output:
bib a fine kettle of fish
bob a fine kettle of fish