How to convert an array reference to an array in Perl?
26,296
Solution 1
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);
Solution 2
Like this:
return @{$reference};
You're then just returning a dereferenced reference.
Solution 3
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!
Related videos on Youtube
Comments
-
chotchki over 3 years
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).
-
tadmc over 12 yearsYou cannot return an array in Perl. (you can however, return the list that an array contains)
-
-
Sergei Krivonos over 5 yearsit returns an empty array this way
-
Sergei Krivonos over 5 yearscan just
return @arr;
?