开发者

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

开发者 https://www.devze.com 2022-12-17 03:56 出处:网络
What\'s the difference between my ($variableName)and my $variableName in Perl? What 开发者_如何学JAVAto the parentheses do?The important effect is when you initialize the variable at the same time tha

What's the difference between my ($variableName) and my $variableName in Perl? What 开发者_如何学JAVAto the parentheses do?


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.


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


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";
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号