计算 Perl 中字符串中非空白字符的数量

Count the number of non-whitespace characters in a string in Perl

我想弄清楚如何计算字符串中的任何和所有非空白字符,以便在下面的示例中我会得到 4 的输出。

my $str = 'A b C $'; 

my $cnt =~ /\S/g;  

print "Char Count: $cnt\n";

这个Is there a Perl shortcut to count the number of matches in a string?没有回答我的问题。

perl -e 'my $str = "A b C"; my $cnt = () = $str =~ /\./gi;  print "Chs: $cnt\n";'
Chs: 0

有人一直想说这个问题是这个问题的重复:Is there a Perl shortcut to count the number of matches in a string?

但是,另一个问题涉及如何匹配特定字符,在他们的情况下,我认为它是一个点。我查看了许多其他试图匹配特定字符的示例,但无法让它们匹配除空格以外的所有字符。

这没有回答我的问题。

$string = "ThisXlineXhasXsomeXx'sXinXit";
$count = ($string =~ tr/X//);
print "There are $count X characters in the string";

这个问题:What do \S, \W, \D stand for in regex? 仅仅定义了各种 Perl 通配符运算符——其中之一(\S 运算符)我试图在我的原始问题中使用但无济于事。但是,它没有演示如何实际使用这些运算符之一来获取字符串中所有非空白字符的计数。

来自perlfaq4 (How can I count the number of occurrences of a substring within a string?)

Another version uses a global match in list context, then assigns the result to a scalar, producing a count of the number of matches.

您还可以从命令行查询 Perl 文档:

perldoc -q count

use warnings;
use strict;

my $str = 'A b C $'; 
my $cnt = () = $str =~ /\S/g;
print "Char Count: $cnt\n";
require 5.014;
use feature qw( unicode_strings );

my $count = () = $str =~ /\S/g;

require 5.014;
use feature qw( unicode_strings );

my $count = 0;
++$count while $str =~ /\S/g;

# Count non-whitespace characters.
my $count = $str =~ tr/\x{0009}\x{000A}\x{000B}\x{000C}\x{000D}\x{0020}\x{0085}\x{00A0}\x{1680}\x{2000}\x{2001}\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}//c;
  • 第一个会占用大量内存。它为每个非白色space 字符创建一个标量。

  • 第二个没有。我不确定它是快了还是慢了。

  • 第三个应该快很多,但是你不能使用预建字符类。

  • require 5.014; use feature qw( unicode_strings );(或仅 use 5.014;)是 \s/\S 正确处理 U+85 NEL 和 U+A0 NBSP 所必需的. (更高版本也可以。)否则,它将“随机”被视为 space 或非 space。

    use feature qw( say );
    
    { local $_ = "abc\x{0085}\x{00A0}\x{2000}"; say scalar( () = /\S/g ); }  # 3
    { local $_ = "abc\x{0085}";                 say scalar( () = /\S/g ); }  # 4?!
    { local $_ = "abc\x{00A0}";                 say scalar( () = /\S/g ); }  # 4?!
    { local $_ = "abc\x{2000}";                 say scalar( () = /\S/g ); }  # 3