看板 Perl 關於我們 聯絡資訊
※ 引述《gecer (gecer)》之銘言: : my $line = "Just another regex hacker, Perl hacker, and that's it!\n"; : while( 1 ) : { : my( $found, $type )= do { : if( $line =~ /\G([a-z]+(?:'[ts])?)/igc ) : { ( $1, "a word" ) } : elsif( $line =~ /\G (\n) /xgc ) : { ( $1, "newline char" ) } : elsif( $line =~ /\G (\s+) /xgc ) : { ( $1, "whitespace" ) } : elsif( $line =~ /\G ( [[:punct:]] ) /xgc ) : { ( $1, "punctuation char" ) } : else : { last; () } : }; : print "Found a $type [$found]\n"; : } : 小弟參考code 如上 請問這裡的do {...}的用意? 非 do {..} while 以下是我的猜測... 這裡一整段看起來類似 $a = ... ? ... : ... 的結構,只不過每一個部份都複雜一些。如果不這麼寫,可能就要重複很多 ($found, $type),變成像這樣: my ( $found, $type ); if( $line =~ /\G([a-z]+(?:'[ts])?)/igc ) { ( $found, $type ) = ( $1, "a word" ) } elsif( $line =~ /\G (\n) /xgc ) { ( $found, $type ) = ( $1, "newline char" ) } elsif( $line =~ /\G (\s+) /xgc ) { ( $found, $type ) = ( $1, "whitespace" ) } elsif( $line =~ /\G ( [[:punct:]] ) /xgc ) { ( $found, $type ) = ( $1, "punctuation char" ) } else { last; () } 所以原作者就用 do {...} 來避免重複。 do { ... } 主要的語意是取得 { ... } 部份「最後執行語句之值」,這部份並不一定是「最末一句」,請稍微留意。 參考: http://perldoc.perl.org/functions/do.html (do BLOCK 的部份) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 126.94.214.19 ※ 文章網址: https://www.ptt.cc/bbs/Perl/M.1519830779.A.AB8.html
herculus6502: d(`・?・)b 03/01 05:34
flu: (^oo^) 03/01 21:13