繁体   English   中英

Perl-分割字符串

[英]Perl - Splitting a string

我正在做一个数组,它满足一个短语的每个单词。 当我尝试将其拆分并打印长度时,控制台会向我提供大量信息,例如111039391231319239188238139123919232913123... (更多行)为什么?

这是我的代码:

$mynames = $texto3;
print $mynames. "\n";
@nameList = split(' ', $texto3);
#print @nameList.length();
for ($to = 0; $to<@nameList.length; $to++){
        if($to<@nameList.length) {
                @nameList[$to] = @nameList[$to] . "_" . @nameList[$to++];
         }
         print $to;
         #print @nameList[$to] . "\n";
 }
 $string_level2 = join(' ', @nameList);
 #print $string_level2;

要获取数组的长度,请使用scalar @nameList而不是@nameList.length

典型的for循环在递增计数时使用小于运算符,例如:

for ( $to = 0; $to < scalar(@nameList); $to++ ) ...

除非您了解副作用,否则切勿使用后增量。 我相信以下内容:

@nameList[$to] = @nameList[$to] . "_" . @nameList[$to++];

...应写为...


    $nameList[$to] = $nameList[$to] . "_" . $nameList[$to + 1];

最后,您使用的比较应考虑边界条件(因为在循环内引用$to + 1 ):

if( $to < (scalar(@nameList) - 1) ) {
  $nameList[ $to ] = $nameList[ $to ] . "_" . $nameList[ $to + 1 ];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM