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?
You can return a value from Perl subroutine as you do in any other programming language. If you are not returning a value from a subroutine then whatever calculation is last performed in a subroutine is automatically also the return value.
A Perl subroutine or function is a group of statements that together performs a task. You can divide up your code into separate subroutines. How you divide up your code among different subroutines is up to you, but logically the division usually is so each function performs a specific task.
A Perl function prototype is zero or more spaces, backslashes, or type characters enclosed in parentheses after the subroutine definition or name. A backslashed type symbol means that the argument is passed by reference, and the argument in that position must start with that type character.
You can pass various arguments to a Perl subroutine like you do in any other programming language and they can be accessed inside the function using the special array @_. Thus the first argument to the function is in [0],thesecondisin_[1], and so on.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With