Re: [問題] 串列問題

看板Perl作者時間14年前 (2011/03/14 14:23), 編輯推噓2(201)
留言3則, 2人參與, 最新討論串2/3 (看更多)
※ 引述《StarTouching (撫星)》之銘言: : 我是Perl新手 有程式基礎 對串列有個小問題.... : 串列給定可以這樣寫: : @ary = (1,2,3); : 或 : @ary = (1..10); : 或 : @ary = @seq; : 而foreach這樣用: : foreach(1,2,3){} : 或 : foreach(1..10){} : 或 : foreach(@seq){} : 這樣有個小問題是 (1,2,3)才能代表串列 那為什麼foreach沒有兩層括弧? : 如果串列的括弧可以被省略 那為什麼 @ary = 1,2,3; 這樣不行? : 我知道Perl是個方便為上的語言, : 但為求方便記憶, 想說還是問問看。 : 請問我該怎麼理解呢? # perldoc perlsyn Statement Modifiers ...略... if EXPR unless EXPR while EXPR until EXPR foreach LIST ^^^^ ...略... The "foreach" modifier is an iterator: it executes the statement once for each item in the LIST (with $_ aliased to each item in turn). print "Hello $_!\n" foreach qw(world Dolly nurse); # perldoc perlop 1. Comma Operator 「,」 ...略... In list context, it’s just the list argument separator, and inserts ^^^^^^^^^^^^^^^^^^^^^^^ both its arguments into the list. These arguments are also evaluated from left to right. ...略... 2. Terms and List Operators ...略... A TERM has the highest precedence in Perl. They include variables, quote and quote-like operators, any expression in parentheses, and any ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function whose arguments are parenthesized. Actually, there aren’t ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ really functions in this sense, just list operators and unary operators ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ behaving as functions because you put parentheses around the arguments. These are all documented in perlfunc. ...略... 3. Range Operators 「..」 Binary ".." is the range operator, which is really two different operators depending on the context. In list context, it returns a list of values counting (up by ones) from the left value to the right value. ...略... 大致上摘錄 perldoc 的內容,應該可以發現其中的差異。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.114.64.130

03/15 23:29, , 1F
所以 1,2,3 跟 1..2 不足以代表串列囉?
03/15 23:29, 1F

03/15 23:29, , 2F
foreach LIST, 那為何 foreach @ary 這樣寫不行?
03/15 23:29, 2F

03/17 18:37, , 3F
@ary=(1,2,3); print foreach @ary;
03/17 18:37, 3F
文章代碼(AID): #1DVRHTbp (Perl)
討論串 (同標題文章)
本文引述了以下文章的的內容:
以下文章回應了本文
完整討論串 (本文為第 2 之 3 篇):
2
3
文章代碼(AID): #1DVRHTbp (Perl)