What's the difference between my ($variableName)
and my $variableName
in Perl? What to the parentheses do?
views:
167answers:
4
+9
A:
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
.
mobrule
2010-01-24 08:08:45
So in essence: the brackets 1. provide list context, and 2. distribute the operator or function across multiple values.
Ether
2010-01-24 08:20:29
#2 is technically incorrect and potentially misleading. It is incorrect in that the way the declaration with the parens works is by defining a lexical list rather than a lexical scalar. It is misleading in that a beginner may read "the brackets... distribute the operator or function across multiple values" and expect `($x, $y) = (1, 2) + 3` to assign the values 4 to `$x` and 5 to `$y` by "distributing the + operator across multiple values". (In actuality, that statement assigns 5 to `$x` and nothing to `$y`.)
Dave Sherohman
2010-01-24 10:24:52
#1 is not completely correct either. The parens on the lefthand side of an assignment provide list context, but that doesn't mean they provide list context everywhere else.
brian d foy
2010-01-24 17:26:17
This answer is wrong and promotes cargo cult programming.
darch
2010-02-03 05:25:52
+2
A:
please look at perdoc perlsub for more information on the my operator. A small excerpt
Synopsis:
my $foo; # declare $foo lexically local
my (@wid, %get); # declare list of variables local
my $foo = "flurp"; # declare $foo lexical, and init it
my @oof = @bar; # declare @oof lexical, and init it
my $x : Foo = $y; # similar, with an attribute applied
ghostdog74
2010-01-24 08:13:06
+2
A:
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.
EmFi
2010-01-24 09:03:26