tags:

views:

167

answers:

4

What's the difference between my ($variableName) and my $variableName in Perl? What to the parentheses do?

+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
So in essence: the brackets 1. provide list context, and 2. distribute the operator or function across multiple values.
Ether
#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
#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
This answer is wrong and promotes cargo cult programming.
darch
+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
+1  A: 
sateesh
+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