Reputation: 4343
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).
Upvotes: 21
Views: 30527
Reputation: 206919
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);
Upvotes: 22
Reputation: 14925
Like this:
return @{$reference};
You're then just returning a dereferenced reference.
Upvotes: 11
Reputation: 46985
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!
Upvotes: 4