Samiron
Samiron

Reputation: 5317

Perl: function returns reference or copy?

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?

Upvotes: 7

Views: 2645

Answers (4)

ikegami
ikegami

Reputation: 386331

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.

Upvotes: 1

Jean
Jean

Reputation: 22725

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

Upvotes: 1

Borodin
Borodin

Reputation: 126742

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

Upvotes: 12

Quentin
Quentin

Reputation: 943996

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.

Upvotes: 4

Related Questions