Perl中的my ($variableName)
和my $variableName
有什麼區別?圓括號做什麼?
回答
中的重要作用是,當你在你聲明它的同時初始化變量:
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
。
所以本質上:括號1.提供列表上下文,並2.分佈多個值的運算符或函數。 – Ether 2010-01-24 08:20:29
#2在技術上不正確,可能會產生誤導。這是不正確的,與parens的聲明工作是通過定義一個詞彙列表而不是詞法標量。這是誤導,初學者可能會讀「括號...分佈在多個值的操作符或函數」,並期望'($ x,$ y)=(1,2)+ 3'分配值4到'通過「在多個值上分配+運算符」,$ x'和5到'$ y'。 (實際上,該語句將5賦給'$ x',沒有給$ y'。) – 2010-01-24 10:24:52
#1也不完全正確。分配左側的元素提供了列表上下文,但這並不意味着他們在其他地方提供了列表上下文。 – 2010-01-24 17:26:17
有關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
由於支架的其他答案和註釋說明使用提供了列表環境變量。 以下是使用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";
簡短的回答是,在一個=
的左側使用時括號力列表環境。
其他每個答案都指出了一個具體情況,這有所不同。實際上,您應該仔細閱讀perlfunc以更好地瞭解如何在列表上下文中調用函數時的不同行爲,而不是標量上下文。
- 1. jquery $ variableName vs $(variableName)
- 2. &VARIABLENAME PHP
- 3. Perl中的'eq'和'=〜'有什麼區別?
- 4. 什麼是「scanf(」%f「,&variableName)中的」&「;」在C編程?
- 5. sed的結果是什麼; //; /; g'和egrep「\ -example(| \:)$ variablename:」give?
- 6. 什麼「ID <someType> variableName」是什麼意思在Objective-C
- 7. 爲什麼在javascript中使用var {VariableName} = require('')?
- 8. Perl中grep和map有什麼區別?
- 9. Perl中'for'和'foreach'有什麼區別?
- 10. 在Strawberry Perl中,perl \ lib和perl \ site \ lib有什麼區別?
- 11. 在htm文件中用%MyVariable%替換%variablename%
- 12. 「perl test.pl」和「./test.pl」有什麼區別?
- 13. 自我和窗戶有什麼區別?
- 14. Node.src = variableName /添加帶有innerHTML和變量問題的HTML圖像
- 15. 在我的程序中Record *和Databse *有什麼區別?
- 16. 在我的Solr模式中,tdouble和tdoubles有什麼區別?
- 17. 我的跨度有什麼區別?
- 18. SQL - 數據庫中已經有一個名爲'variableName'的對象
- 19. Perl正則表達式中的\ 1和$ 1有什麼區別?
- 20. Perl中的open和sysopen有什麼區別?
- 21. Perl中的system,exec和反引號有什麼區別?
- 22. Perl中的對象和類之間有什麼區別?
- 23. Perl中的哈希和哈希引用有什麼區別?
- 24. C和Perl中的system()有什麼區別?
- 25. Perl中的新Some :: Class和Some :: Class-> new()有什麼區別?
- 26. Perl中的子程序和腳本有什麼區別?
- 27. 有什麼區別`和$(Bash中有什麼區別?
- 28. 在Perl中`use base`和@ISA有什麼區別?
- 29. 函數調用和goto&NAME在Perl中有什麼區別?
- 30. 在Perl中,`use lib`和`lib-> import`有什麼區別?
有趣的Perl Monks回答[here](http://www.perlmonks.org/?node_id=693666)最終歸結爲聲明 - 作業中parens的使用,作爲最終運行的粗略操作優先。 – ruffin 2015-02-09 21:36:31
完整,詳細的答案在這裏:[小型教程:標量VS列表分配運營商](http://www.perlmonks.org/?node_id=790129)。 – ikegami 2017-03-17 19:16:06