Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arrays to functions in Perl

I think I have misunderstood some aspects of argument passing to functions in Perl. What's the difference between func(\@array) and func(@array)?

AFAIK, in both functions, arguments are passed by reference and in both functions we can change the elements of @array in the main program. So what's the difference? When should we use which?

@array = (1,2,3);
func(@array);
func(\@array);

sub func {
    ...
}

Also, how do I imitate pass-by-value in Perl? Is using @_ the only way?

like image 405
aminfar Avatar asked Aug 30 '11 01:08

aminfar


People also ask

How do I pass multiple arrays to a subroutine in Perl?

You can't pass arrays to functions. Functions can only accept a lists of scalars for argument. As such, you need to pass scalars that provide sufficient data to recreate the arrays. The simplest means of doing so is passing references to the arrays.

How do I pass a subroutine list in Perl?

Passing Lists or Arrays to a Subroutine: An array or list can be passed to the subroutine as a parameter and an array variable @_ is used to accept the list value inside of the subroutine or function. Example 1: Here a single list is passed to the subroutine and their elements are displayed.


1 Answers

It's impossible to pass arrays to subs. Subs take a list of scalars for argument. (And that's the only thing they can return too.)

You can pass a reference to an array:

func(\@array)

You can pass the elements of an array:

func(@array)

When should we use which?

If you want to pass more than just the elements of the array (e.g. pass $x, $y and @a), it can become tricky unless you pass a reference.

If you're going to process lists (e.g. sum mysub grep { ... } ...), you might not want to pass a reference.

If you want to modify the array (as opposed to just modifying the existing elements of the array), you need to pass a reference.

It can be more efficient to pass a reference for long arrays, since creating and putting one reference on the stack is faster than creating an alias for each element of a large array. This will rarely be an issue, though.

It's usually decided by one of the first two of the above. Beyond that, it's mostly a question of personal preference.


Also, how do I imitate pass-by-value in Perl?
sub foo {
   my ($x) = @_;   # Changing $x doesn't change the argument.
   ...
}

sub foo {
   my @a = @_;   # Changing @a or its contents
   ...           #    doesn't change the arguments.
}
like image 57
ikegami Avatar answered Sep 21 '22 17:09

ikegami