4

I got the following code:

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

Can anyone tell me what $;$ means?

Jonathan Cast
  • 4,569
  • 19
  • 34
for_stack
  • 21,012
  • 4
  • 35
  • 48

1 Answers1

11

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.

Community
  • 1
  • 1
simbabque
  • 53,749
  • 8
  • 73
  • 136
  • 4
    Part of the reason they're considered bad practice is the word `prototype`. In other programming languages, it means something else. – Sobrique Oct 14 '15 at 13:02
  • That's helpful. thanks a lot! – for_stack Oct 14 '15 at 13:03
  • 1
    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. (They're power tools; read the manual and don't use them unless you mean it.) – The Sidhekin Oct 15 '15 at 01:18