RTF RTF - 1 year ago 42
Perl Question

What does the dollar character in the brackets of a Perl subroutine mean?

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?


It is a subroutine prototype.

The single $ means that the sub will only accept a single scalar value.

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 contexts - 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.