What's the difference between my ($variableName)
and my $variableName
in Perl? What to the parentheses do?
my is used for local variables, whereas our is used for global variables.
There is a strange scalar variable called $_ in Perl, which is the default variable, or in other words the topic. In Perl, several functions and operators use this variable as a default, in case no parameter is explicitly used. In general, I'd say you should NOT see $_ in real code.
my keyword in Perl declares the listed variable to be local to the enclosing block in which it is defined. The purpose of my is to define static scoping. This can be used to use the same variable name multiple times but with different values.
Perl has three main variable types: scalars, arrays, and hashes.
The important effect is when you initialize the variable at the same time that you declare it:
my ($a) = @b; # assigns $a = $b[0] my $a = @b; # assigns $a = scalar @b (length of @b)
The other time it is important is when you declare multiple variables.
my ($a,$b,$c); # correct, all variables are lexically scoped now my $a,$b,$c; # $a is now lexically scoped, but $b and $c are not
The last statement will give you an error if you use strict
.
The short answer is that parentheses force list context when used on the left side of an =
.
Each of the other answers point out a specific case where this makes a difference. Really, you should read through perlfunc to get a better idea of how functions act differently when called in list context as opposed to scalar context.
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