Reputation: 6494
I've inherited some Perl code and occasionally I see subroutines defined like this:
sub do_it($) {
...
}
I can't find the docs that explain this. What does the dollar symbol in brackets mean?
Upvotes: 5
Views: 1565
Reputation: 27207
It is a subroutine prototype.
The single $
means that the sub will only accept a single scalar value, and will interpret other types using scalar context. For instance, if you pass an array as the param e.g. do_it(@array)
, Perl will not expand @array
into a list, but instead pass in the length of the array to the subroutine body.
This is sometimes useful as Perl can give an error message when the subroutine is called incorrectly. Also, Perl's interpreter can use the prototypes to disambiguate method calls. I have seen the &
symbol (for code block prototype) used quite neatly to write native-looking routines that call to anonymous code.
However, it only works in some situations - e.g. it doesn't work very well in OO Perl. Hence its use is a bit patchy. Perl Best Practices recommends against using them.
Upvotes: 7
Reputation: 2550
The ($)
is called a subroutine prototype.
See the PerlSub man page for more information: http://perldoc.perl.org/perlsub.html#Prototypes
Prototyping isn't very common nowadays. Best Practice is not using it.
Upvotes: 6