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!

Share:
26,296

Related videos on Youtube

chotchki
Author by

chotchki

I am an applications developer, mainly in Linux.

Updated on April 02, 2020

Comments

  • chotchki
    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
      tadmc over 12 years
      You cannot return an array in Perl. (you can however, return the list that an array contains)
  • Sergei Krivonos
    Sergei Krivonos over 5 years
    it returns an empty array this way
  • Sergei Krivonos
    Sergei Krivonos over 5 years
    can just return @arr;?

Related