Re: [問題] 關於map的問題

看板Perl作者 (檸檬汁)時間18年前 (2006/06/19 17:04), 編輯推噓2(200)
留言2則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《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
thanks!
06/19 19:43, 1F

07/08 03:34, , 2F
這個問題真有趣
07/08 03:34, 2F
文章代碼(AID): #14bcYKGM (Perl)
文章代碼(AID): #14bcYKGM (Perl)