Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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?

like image 956
RTF Avatar asked Apr 27 '16 10:04

RTF


People also ask

How do I return a value from a subroutine in Perl?

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.

What is subroutine in Perl?

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.

What is a Perl prototype?

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.

How do you pass arguments in Perl subroutine?

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.


1 Answers

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.

like image 151
Neil Slater Avatar answered Sep 30 '22 07:09

Neil Slater