Reputation: 19582
I want to clear my understanding on the following.
Assume I have a Perl module with a function that expects 3 parameters.
E.g. in the function:
my ($a, $b, $c) = @_;
Now this function is being called by 2 different other scripts.
One of the scripts needs some "additional" functionality so. If I pass some e.g. 2 extra parameters to the function e.g.
my ($a, $b, $c, $d, $e) = @_;
and use them if they are defined, this would not cause any problems right?
My main concern is, there is no function signature or similar in perl right? So I can pass any arguments
Upvotes: 2
Views: 441
Reputation: 39158
Answering the subject part of the question only, this is for the benefit of people coming from search engines:
Signatures are available in standard Perl from version 20. CPAN modules offer more functionality:
I recommend Kavorka.
Upvotes: 3
Reputation: 54371
You can pass as many arguments as you want. All the ones you do not assign will just not be used. In the assignment form you are using they will just remain in @_
.
sub foo {
my ($a, $b, $c) = @_;
}
foo(1, 2, 3, 4);
In this case, 4
will never be assigned to a variable, but it is still there.
If you call it like foo(1, 2)
that does no harm either, unless you are doing something with $c
.
You cannot, however, define two different behaviors for foo
with a certain number of parameters as two different subs with the same name. You would need to build this yourself in one sub. It does not always make sense, though.
sub foo {
my ($x, $y, $z) = @_;
if ($z) {
return $x + $y + $z;
else {
return $x - $y;
}
}
Upvotes: 3
Reputation: 57640
In Perl, every sub takes a list of scalars, and returns a list of scalars. In C-ish terms, this could be written
SV** some_sub(SV** args);
Where SV*
is the type of a scalar variable.
There are ways to constrain the parameters: e.g using the syntactic sugar of Method::Signatures
, or prototypes (please don't use prototypes).
The list assignment my ($a, $b, $c, $d, $e) = @_;
works regardless of the size of the array @_
. If the RHS (right hand side) has fewer elements that the LHS, then the scalars on the left are undef
. E.g.
sub foo {
my ($x, $y, $z) = @_;
say "x is ", $x // "undef";
say "y is ", $y // "undef";
say "z is ", $z // "undef";
}
say "foo(1)";
foo(1);
say "foo(1, 2, 3)";
foo(1, 2, 3);
say "foo(1 .. 10_000)";
foo(1 .. 10_000); # ten thousand arguments!
Output:
foo(1)
x is 1
y is undef
z is undef
foo(1, 2, 3)
x is 1
y is 2
z is 3
foo(1 .. 10_000)
x is 1
y is 2
z is 3
Upvotes: 3