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 most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }
=~ is the Perl binding operator. It's generally used to apply a regular expression to a string; for instance, to test if a string matches a pattern: if ($string =~ m/pattern/) {
The @_ variable is an array that contains all the parameters passed into a subroutine. The parentheses around the $string variable are absolutely necessary. They designate that you are assigning variables from an array.
The @_
variable is an array that contains all the parameters passed into a subroutine.
The parentheses around the $string
variable are absolutely necessary. They designate that you are assigning variables from an array. Without them, the @_
array is assigned to $string
in a scalar context, which means that $string
would be equal to the number of parameters passed into the subroutine. For example:
sub foo {
my $bar = @_;
print $bar;
}
foo('bar');
The output here is 1--definitely not what you are expecting in this case.
Alternatively, you could assign the $string
variable without using the @_
array and using the shift
function instead:
sub foo {
my $bar = shift;
print $bar;
}
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.
When you encounter a special (or punctuation) variable in Perl, check out the perlvar documentation. It lists them all, gives you an English equivalent, and tells you what it does.
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