Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 224
Samiron Avatar asked Oct 12 '12 15:10

Samiron


People also ask

Does Perl pass by value or reference?

Perl always passes by reference. It's just that sometimes the caller passes temporary scalars. Perl passes by reference.

What is return in Perl?

Perl provides a return statement which can be used to exit a function, and provide a value when a function call is evaluated. In the absence of a return statement, the value of a function call will be the last expression which was evaluated in the body of the function.

How do I return a value in Perl?

To return a value from a subroutine, block, or do function in Perl, we use the return() function. The Value may be a scalar, a list, or a hash value. Its context is selected at runtime.

How do I return an array in Perl?

return() function in Perl returns Value at the end of a subroutine, block, or do function. Returned value might be scalar, array, or a hash according to the selected context.


1 Answers

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

like image 122
Borodin Avatar answered Sep 27 '22 18:09

Borodin