Re: [问题] Perl do 用法

楼主: gecer (gecer)   2018-03-10 19:43:56
※ 引述《gugod (啊)》之铭言:
: ※ 引述《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 的部份)
$A="a";
my ($s1,$s2)=do {
if ($A=="a")
{("s1","s2")}
if ($A!="a")
{("s3","s4")}
};
print "S1=$s1 S2=$s2";
小弟模仿此用法 但是输出的s1 s2却为空 请问这里do是否没有执行到?

Links booklink

Contact Us: admin [ a t ] ucptt.com