Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array reference to an array in Perl?

Tags:

perl

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

like image 622
chotchki Avatar asked Apr 01 '11 14:04

chotchki


2 Answers

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);
like image 132
Mat Avatar answered Oct 28 '22 05:10

Mat


Like this:

return @{$reference};

You're then just returning a dereferenced reference.

like image 22
Paul Beckingham Avatar answered Oct 28 '22 05:10

Paul Beckingham