Perl: Return anonymous array from a subroutine

时间:2016-02-12 19:41:36

标签: perl

I'm trying to return an anonymous array from a subroutine, however, when dumping the returned variable I only see one value (I'm expecting two).

Here is my code:

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

my $fruits_ref = generate_fruits();
print "Fruits: " . Dumper($fruits_ref) . "\n";

sub generate_fruits
{
    return ("Apple", "Orange");
}

This outputs:

Fruits: $VAR1 = 'Orange';

How do I get the subroutine to return that array ref?

2 个答案:

答案 0 :(得分:7)

Anonymous arrays are constructed with square brackets.

return [ 'Apple', 'Orange' ]

答案 1 :(得分:2)

You're not returning an array (or a reference to array), you're returning a list. A reference to anonymous array is ["Apple", "Orange"]

List becomes its last element when you pass it to scalar context. To pass to list context, you could do

my @fruits = generate_fruits();

But that is likely not what you need - you seem to need a reference. For that, just use square brackets.

Oh, another alternative is

my $fruits_ref = [generate_fruits()];