如何计算Perl中字符串开头的空格量?
我现在有:
$temp = rtrim($line[0]);
$count = ($temp =~ tr/^ //);
Run Code Online (Sandbox Code Playgroud)
但这给了我所有空间的数量.
Can*_*ice 11
$str =~ /^(\s*)/;
my $count = length( $1 );
Run Code Online (Sandbox Code Playgroud)
如果你只想要实际的空格(而不是空格),那就是:
$str =~ /^( *)/;
Run Code Online (Sandbox Code Playgroud)
编辑:tr不起作用的原因是它不是正则表达式运算符.您正在做的$count = ( $temp =~ tr/^ // );是替换所有实例^和 with itself (see comment below by cjm), then counting up how many replacements you've done. tr并不^认为"嘿,这是字符串伪字符的开头",它将其视为"嘿,这是一个^".
您可以使用 获取匹配的偏移量@-。如果您搜索非空白字符,这将是字符串开头的空白字符数:
#!/usr/bin/perl
use strict;
use warnings;
for my $s ("foo bar", " foo bar", " foo bar", " ") {
my $count = $s =~ /\S/ ? $-[0] : length $s;
print "'$s' has $count whitespace characters at its start\n";
}
Run Code Online (Sandbox Code Playgroud)
或者,更好的是,使用@+来查找空格的结尾:
#!/usr/bin/perl
use strict;
use warnings;
for my $s ("foo bar", " foo bar", " foo bar", " ") {
$s =~ /^\s*/;
print "$+[0] '$s'\n";
}
Run Code Online (Sandbox Code Playgroud)