I was glancing through some code I had written in my Perl class and I noticed this.
my ($string) = @_; my @stringarray = split(//, $string);
I am wondering two things: The first line where the variable is in parenthesis, this is something you do when declaring more than one variable and if I removed them it would still work right?
The second question would be what does the @_ do?
The
@_variable is an array that contains all the parameters passed into a subroutine.The parentheses around the
$stringvariable are absolutely necessary. They designate that you are assigning variables from an array. Without them, the@_array is assigned to$stringin a scalar context, which means that$stringwould be equal to the number of parameters passed into the subroutine. For example:The output here is 1–definitely not what you are expecting in this case.
Alternatively, you could assign the
$stringvariable without using the@_array and using theshiftfunction instead:Using one method over the other is quite a matter of taste. I asked this very question which you can check out if you are interested.