Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does $;$ mean in a Perl function definition? [duplicate]

Tags:

perl

I got the following code:

sub deg2rad ($;$) { my $d = _DR * $_[0]; $_[1] ? $d : rad2rad($d) }

Can anyone tell me what $;$ means?

like image 260
for_stack Avatar asked Dec 18 '22 23:12

for_stack


1 Answers

The stuff in parenthesis behind a sub declaration is called a prototype. They are explained in perlsub. In general, you can use them to have limit compile-time argument checking.

The particular ($;$) is used for mandatory arguments.

A semicolon (; ) separates mandatory arguments from optional arguments. It is redundant before @ or % , which gobble up everything else

So here, the sub has to be called with at least one argument, but may have a second one.

If you call it with three arguments, it will throw an error.

use constant _DR => 1;
sub rad2rad       {@_}
sub deg2rad ($;$) { my $d = _DR * $_[0]; $_[1] ? $d : rad2rad($d) }

print deg2rad(2, 3, 4);

__END__

Too many arguments for main::deg2rad at scratch.pl line 409, near "4)"
Execution of scratch.pl aborted due to compilation errors.

Note that prototypes don't work with method calls like $foo->frobnicate().

In general, prototypes are considered bad practice in modern Perl and should only be used when you know exactly what you are doing.

The short and to the point way The Sidhekin used in their comment below sums it up nicely:

The most important reason they're considered bad practice, is that people who don't know exactly what they are doing, are trying to use them for something that they're not.

See this question and its answers for detailed explanations and discussion on that topic.

like image 134
simbabque Avatar answered Dec 21 '22 11:12

simbabque