21

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).

1
  • 2
    You cannot return an array in Perl. (you can however, return the list that an array contains) Commented Apr 1, 2011 at 21:29

3 Answers 3

22

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);
Sign up to request clarification or add additional context in comments.

1 Comment

can just return @arr;?
11

Like this:

return @{$reference};

You're then just returning a dereferenced reference.

1 Comment

it returns an empty array this way
4

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.