Re: [問題] 串列問題
※ 引述《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
03/15 23:29, 1F
→
03/15 23:29, , 2F
03/15 23:29, 2F
推
03/17 18:37, , 3F
03/17 18:37, 3F
討論串 (同標題文章)
Perl 近期熱門文章
PTT數位生活區 即時熱門文章