Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get multiple arguments in Perl functions?

Tags:

perl

shift

In my code, I'm been using the fairly primitive method of extraction parameters from a function call as follows:

sub addSix ($$$$$$) {
    my ($a, $b, $c, $d, $e, $f) = (shift, shift, shift, shift, shift, shift);
    return $a + $b + $c + $d + $e + $f;
}

print addSix (1, 2, 3, 4, 5, 6) . "\n";

(forget the primitive code, the salient bit is the multiple shift calls).

Now that seems rather messy to me and I though Perl may have something like:

my ($a, $b, $c, $d, $e, $f) = shift (6);

or something similar.

But I cannot find anything like that. I know I can use arrays for this but I think I'd still have to unpack the array into individual scalars. That wouldn't be too bad for the example case above, where the six parameters are similar, but I'm more interested in the case where they're not really suitable as an array.

How can you extract parameters without ending up with a morass of shift keywords?

like image 601
paxdiablo Avatar asked Jan 12 '12 07:01

paxdiablo


People also ask

How do I return multiple values from a function in Perl?

You can also assign an array to hold the multiple return values from a Perl function. You do that like this: sub foo { return ('aaa', 'bbb', 'ccc'); } (@arr) = &foo(); print "@arr\n"; As you can see, most of the code is the same, except I now assign an array ( @arr ) to contain the three return values from my function.

Is it possible to pass multiple arguments to a function?

Some functions are designed to return values, while others are designed for other purposes. We pass arguments in a function, we can pass no arguments at all, single arguments or multiple arguments to a function and can call the function multiple times.


2 Answers

You can simply type:

my ($a, $b, $c, $d, $e, $f) = (@_);

If you didn't have that prototype, and if that sub got called with more than six arguments, the ones after the sixth are simply "not matched", $f would be set to the sixth argument.

If you want to catch all the arguments after the sixth, you can do it like this.

my ($a, $b, $c, $d, $e, $f, @others) = (@_);

If your list of scalars is longer than the list on the right side, the last elements will be undef.

like image 129
Mat Avatar answered Sep 19 '22 14:09

Mat


The use of prototypes is highly discouraged unless there is a real need for it.

As always with Perl, there is more than one way to do it.

Here's one way to guarantee adding only the first six parameters that are passed:

use List::Util 'sum';

sub addSix { sum @_[0..5] }

Or if you like self-documenting code:

sub addSix {

    my @firstSix = @_[0..5];  # Copy first six elements of @_
    return sum @firstSix;
}
like image 35
Zaid Avatar answered Sep 20 '22 14:09

Zaid