1

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?

5
  • 2
    You're not returning an array, you're returning a list. An array is ["Apple", "Orange"] Commented Feb 12, 2016 at 19:43
  • Is it possible to return the entire list? How might I unpack the list? Commented Feb 12, 2016 at 19:44
  • $fruits_ref = [ generate_fruits() ] Commented Feb 12, 2016 at 19:46
  • 1
    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()]; Commented Feb 12, 2016 at 19:47
  • Thanks @arkadiy. If you post a answer I'd be happy to accept. Commented Feb 12, 2016 at 19:50

2 Answers 2

8

Anonymous arrays are constructed with square brackets.

return [ 'Apple', 'Orange' ]
Sign up to request clarification or add additional context in comments.

Comments

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()];

1 Comment

Nit: ["Apple", "Orange"] is not an array; it's a reference to an anonymous array. An array would be @array = ("Apple", "Orange").

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.