I want to pass several parameters, one of which is optional, to a function. The only way to do it that I know is using a list (@) as a parameter. Thus, it contents nothing or 1 element (will never be undef), so that I can use the following code:
sub someFunction($$@) {
my ( $oblig_param1, $oblig_param2, $option_param ) = @_;
...
}
This code works, but I feel that maybe it's not the best workaround.
Are there any other ways to do it?
Thank you.
To declare optional function parameters in JavaScript, there are two approaches: Using the Logical OR operator ('||'): In this approach, the optional parameter is Logically ORed with the default value within the body of the function. Note: The optional parameters should always come at the end on the parameter list.
You can pass various arguments to a Perl subroutine like you do in any other programming language and they can be accessed inside the function using the special array @_. Thus the first argument to the function is in [0],thesecondisin_[1], and so on.
Using the Parameter Array (@_) Perl lets you pass any number of parameters to a function. The function decides which parameters to use and in what order.
The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.
Prototypes (the ($$@)
part of your sub declaration) are optional themselves. They have a very specific use, and if you don't know what it is, it is better to not use it. From perlsub:
...the intent of this feature is primarily to let you define subroutines that work like built-in functions
Just remove the prototype from your sub declaration, and you can use whatever arguments you like.
sub someFunction {
my ( $oblig_param1, $oblig_param2, $option_param ) = @_;
if (defined $option_param) {
# do optional things
}
$option_param //= "default optional value";
....
}
You can use a semicolon in the prototype to indicate the end of the required parameters:
sub someFunction($$;$) {
my ( $oblig_param1, $oblig_param2, $option_param ) = @_;
...
}
The ;
is optional before a @
or %
, which, according to the docs, "gobbles up everything else".
EDIT: As DVK points out in a comment (and TLP emphasizes in another answer here), you are probably best off simply avoiding prototypes:
sub someFunction {
my ( $oblig_param1, $oblig_param2, $option_param ) = @_;
...
}
Perl prototypes have their uses (mostly to supply implicit context coercion to arguments, as Perl's built-in functions do). They should not be used as a mechanism to check that function are called with the correct number and type of arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With