Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a variable optional in a perl sub prototype?

Tags:

perl

I'd like to understand if it's possible to have a sub prototype and optional parameters in it. With prototypes I can do this:

sub some_sub (\@\@\@) {
    ...
}

my @foo = qw/a b c/;
my @bar = qw/1 2 3/;
my @baz = qw/X Y Z/;

some_sub(@foo, @bar, @baz);

which is nice and readable, but the minute I try to do

some_sub(@foo, @bar);

or even

some_sub(@foo, @bar, ());

I get errors:

Not enough arguments for main::some_sub at tablify.pl line 72, near "@bar)"

or

Type of arg 3 to main::some_sub must be array (not stub) at tablify.pl line 72, near "))"

Is it possible to have a prototype and a variable number of arguments? or is something similar achievable via signatures?

I know it could be done by always passing arrayrefs I was wondering if there was another way. After all, TMTOWTDI.

like image 593
simone Avatar asked Jun 08 '26 06:06

simone


1 Answers

All arguments after a semi-colon are optional:

sub some_sub(\@\@;\@) {
}
like image 57
Guido Flohr Avatar answered Jun 10 '26 19:06

Guido Flohr