2010-01-24 65 views
22

Perl中的my ($variableName)my $variableName有什麼區別?圓括號做什麼?

+1

有趣的Perl Monks回答[here](http://www.perlmonks.org/?node_id=693666)最終歸結爲聲明 - 作業中parens的使用,作爲最終運行的粗略操作優先。 – ruffin 2015-02-09 21:36:31

+0

完整,詳細的答案在這裏:[小型教程:標量VS列表分配運營商](http://www.perlmonks.org/?node_id=790129)。 – ikegami 2017-03-17 19:16:06

回答

19

中的重要作用是,當你在你聲明它的同時初始化變量:

my ($a) = @b; # assigns $a = $b[0] 
my $a = @b;  # assigns $a = scalar @b (length of @b) 

其他時間是很重要的是當你聲明多個變量。

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 

最後一條語句會給你一個錯誤,如果你use strict

+10

所以本質上:括號1.提供列表上下文,並2.分佈多個值的運算符或函數。 – Ether 2010-01-24 08:20:29

+2

#2在技術上不正確,可能會產生誤導。這是不正確的,與parens的聲明工作是通過定義一個詞彙列表而不是詞法標量。這是誤導,初學者可能會讀「括號...分佈在多個值的操作符或函數」,並期望'($ x,$ y)=(1,2)+ 3'分配值4到'通過「在多個值上分配+運算符」,$ x'和5到'$ y'。 (實際上,該語句將5賦給'$ x',沒有給$ y'。) – 2010-01-24 10:24:52

+3

#1也不完全正確。分配左側的元素提供了列表上下文,但這並不意味着他們在其他地方提供了列表上下文。 – 2010-01-24 17:26:17

4

有關my運營商的更多信息,請參閱perdoc perlsub。這裏有一個小摘錄:

簡介:

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 
1

由於支架的其他答案和註釋說明使用提供了列表環境變量。 以下是使用perl函數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"; 

4

簡短的回答是,在一個=的左側使用時括號力列表環境。

其他每個答案都指出了一個具體情況,這有所不同。實際上,您應該仔細閱讀perlfunc以更好地瞭解如何在列表上下文中調用函數時的不同行爲,而不是標量上下文。

相關問題