7

Im a newbie in perl. So the question might sound something naive.

I have two following functions

#This function will return the reference of the array
sub getFruits1
{
    my @fruits = ('apple', 'orange', 'grape');
    return \@fruits;
}

But in the following case?

#How it returns?
sub getFruits2
{
    my @fruits = ('apple', 'orange', 'grape');
    return @fruits;
}

Will getFruits2 return a reference and a new copy of that array will be created?

Samiron
  • 5,169
  • 2
  • 28
  • 55

4 Answers4

12

The getFruits2 subroutine returns a list, which can be assigned to a new array like this

my @newfruits = getFruits2();

And yes, it will produce a copy of the data in the array

Borodin
  • 126,100
  • 9
  • 70
  • 144
  • Great!! your answer taught me the difference between array and list also. I never thought of this earlier. After a quick googling I also got this http://stackoverflow.com/a/6024268/1160106. Thanks. – Samiron Oct 12 '12 at 17:38
  • See also [What is the difference between a list and an array?](http://perldoc.perl.org/perlfaq4.html#What-is-the-difference-between-a-list-and-an-array?) in perlfaq4 – Borodin Oct 12 '12 at 19:03
4

getFruits1 will return a reference to an array. The \ creates a reference.

getFruits2 will return a list of the values in @fruits. It won't return a reference. You'll only get a copy of the array if you assign the return value to an array.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

getFruits1 returns a reference.No new array is created.

getFruits2 returns a list

An example of Perl referencing

#!/usr/bin/perl -w 
use strict;

my @array = ('a','b','c');
printf("[%s]\n",join('',@array));
my $ref=\@array;
${@{$ref}}[0]='x'; # Modifies @array using reference
printf("[%s]\n",join('',@array));
Jean
  • 21,665
  • 24
  • 69
  • 119
1

The only thing that can be returned by a sub is a list of scalars. Arrays can't be returned.

\@fruits

evaluates to a reference, so

return \@fruits;

returns a reference. In list context,

@fruits

evaluates to a list of the elements of @fruits, so

return @fruits;

returns a list of the elements of @fruits if the sub is evaluated in list context.

ikegami
  • 367,544
  • 15
  • 269
  • 518