John
John

Reputation: 5239

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

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

Upvotes: 25

Views: 5594

Answers (4)

sateesh
sateesh

Reputation: 28673

As the other answer and comments explain usage of brackets provide list context to the variable. Below is a code snippet that provides some more explanation by making use of the Perl function split.

use strict;

my $input = "one:two:three:four";

# split called in list context
my ($out) = split(/:/,$input);
# $out contains string 'one' 
#(zeroth element of the list created by split operation)
print $out,"\n";

# split called in scalar context
my $new_out = split(/:/,$input);
# $new_out contains 4 (number of fields found)
print $new_out,"\n";

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342373

Please look at perdoc perlsub for more information on the my operator. Here's 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

Upvotes: 5

EmFi
EmFi

Reputation: 23450

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.

Upvotes: 5

mob
mob

Reputation: 118605

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.

Upvotes: 21

Related Questions