Re: [問題] 關於map的問題
※ 引述《LiloHuang (夏夜晚風)》之銘言:
: ※ 引述《HXZ (衝了啊)》之銘言:
: : 有一個map的問題不太懂
: : 程式如下:
: : @test = (1, 2, 3, a, b, c, d)
: : @r1 = map {/\D/} @test;
這個map傳回的是((), (), (), (1), (1), (1), (1)),即(1, 1, 1, 1)
: : print "@r1\n";
: : 最後結果是: 1 1 1 1
: : 我不懂為什麼結果不是0 0 0 1 1 1 1
: : 可以請各位幫我解惑一下嗎...orz 謝謝
(恕刪)
: 推 HXZ:這個寫法我知道... 06/13 17:45
: → HXZ:原來那樣是因為比對失敗傳回的是undef嗎? 06/13 17:47
比對失敗傳回的是(),即空list
: 推 LiloHuang:應該是比對沒回傳東西 06/13 19:47
: → LiloHuang:因為$r1[0]的值已經1了 如果是undef $r1[0]不會是這樣 06/13 19:49
: → HXZ:就是我覺得不解的地方...總覺得應該要有東西... 06/13 19:52
: → HXZ:其實這個程式只是我在看map grep時隨便寫看看的..沒想到會這樣 06/13 19:54
: 推 HXZ:map {!/\D/} @test 結果print出三個1 ...orz 06/13 20:30
!會將/\D/傳回的結果scalar化再取反,
所以這個map(在print的list context下)傳回的是三個1和四個undef才對,
如果把這個map放在scalar的context下,可以發現結果是7
perldoc perlop
...
If the "/g" option is not used, "m//" in list context returns a
list consisting of the subexpressions matched by the parentheses
in the pattern, i.e., ($1, $2, $3...). (Note that here $1 etc.
are also set, and that this differs from Perl 4's behavior.)
When there are no parentheses in the pattern, the return value
is the list "(1)" for success. With or without parentheses, an
empty list is returned upon failure.
...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 143.89.144.107
推
06/19 19:43, , 1F
06/19 19:43, 1F
推
07/08 03:34, , 2F
07/08 03:34, 2F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):