4 ms·
For many years Perl subroutines didn't even have method signatures so you had to unroll @ on the first line of every sub. I think even today it may still be con
by cutler 6y ago
For many years Perl subroutines didn't even have method signatures so you had to unroll @ on the first line of every sub. I think even today it may still be considered experimental. Jeez!
- benbristow 6y agoYeah it's pretty archaic. Shortest hand way of doing it is like this: sub method { my ($self, $a, $b, $c) = @_; } $self being a reference to the current module (ala Javascript's 'this')
- cutler 6y ago$self is only for OOP so not needed in a regular subroutine.
- daotoad 6y agoThe reason for the @_ is that it is a simple way to get both pass by value and pass by reference semantics. The values in @_ are aliased to the values in the subroutine call. Most of the time, you want pass by value semantics, so you unpack the array and copy the values into function variables. If you want to modify an argument, it's typically passed in as a reference, and you can mess with it that way. However, there are times when it would be horribly inefficient to make those copies, or when you need to do some magic (generally best avoided in 99.999% of your code), that this makes possible. Also, since Perl functions are always variadic, it means that it's easy to work with a variable list of arguments in a function. For example, if you are expecting a list of key value pairs for your function, you can simply write: my %args = @_ Making signatures default will be a big improvement, but the power of the simple abstraction @_ provides should not be underestimated. It's actually an elegant solution to a complex problem.