I know I can create an array and a reference to an array as follows:
my @arr = ();
my $rarr = \@arr;
I can then iterate over the array reference as follows:
foreach my $i (@{$rarr}){
}
Is there a way to copy or convert the array ref to a normal array so I can return it from a function? (Ideally without using that foreach loop and a push).
-
2You cannot return an array in Perl. (you can however, return the list that an array contains)tadmc– tadmc2011年04月01日 21:29:40 +00:00Commented Apr 1, 2011 at 21:29
3 Answers 3
You have the answer in your question :-)
use warnings;
use strict;
sub foo() {
my @arr = ();
push @arr, "hello", ", ", "world", "\n";
my $arf = \@arr;
return @{$arf}; # <- here
}
my @bar = foo();
map { print; } (@bar);
1 Comment
return @arr;?Like this:
return @{$reference};
You're then just returning a dereferenced reference.
1 Comment
you can copy the array simply by assigning to a new array:
my @copy_of_array = @$array_ref;
BUT, you don't need to do that just to return the modified array. Since it's a reference to the array, updating the array through the reference is all you need to do!