我想逐个字符地解析字符串。我使用perl来做到这一点。有没有办法我们可以从字符串的第一个字符开始,然后逐个字符循环。现在我已经将字符串拆分成一个数组,我就是厕所[ping通过数组。
$var="junk shit here. fkuc lkasjdfie.";
@chars=split("",$var);
但是不是在自身之前拆分整个字符串,是否有任何描述符指向字符串的第一个字符然后遍历每个字符?有没有办法做到这一点?
答案 0 :(得分:2)
my $var = "junk sit here. fkuc lkasjdfie.";
while ($var =~ /(.)/sg) {
my $char = $1;
# do something with $char
}
或
for my $i (1 .. length $var) {
my $char = substr($var, $i-1, 1);
}
当有标记时,substr
方法的效果优于while
,
use Benchmark qw( cmpthese ) ;
my $var = "junk sit here. fkuc lkasjdfie." x1000;
cmpthese( -5, {
"while" => sub{
while ($var =~ /(.)/sg) {
my $char = $1;
# do something with $char
}
},
"substr" => sub{
for my $i (1 .. length $var) {
my $char = substr($var, $i-1, 1);
}
},
});
结果
Rate while substr
while 56.3/s -- -53%
substr 121/s 114% --
答案 1 :(得分:1)
我不知道它是否比分割它更快但是你可以复制reverse它和chop它,直到它为空。
$a = "dude";
$b = reverse($a);
for ($i = length($b) ; $i>0 ; $i--) {
print chop $b; print "\n";'
}
答案 2 :(得分:1)
这可以是脚本/正则表达式的骨架:
use strict;
use warnings;
use Data::Dumper qw(Dumper);
my $str = "The story of Dr. W. Fletcher who is a dentist. The hero of the community.";
my @sentences = split /(?<!(Dr| \w))\./, $str;
print Dumper \@sentences;
输出是:
$VAR1 = [
'The story of Dr. W. Fletcher who is a dentist',
undef,
' The hero of the community'
];