Perl中可以使用正则表达式和内置函数来计算字符串中空格的数量。
方法一:使用正则表达式匹配空格,然后使用数组上下文将匹配结果保存到数组中,最后返回数组的长度。
use strict;use warnings;my $str = "Hello world!";my @spaces = $str =~ /\s/g;my $count = scalar @spaces;print "空格数量:$count\n";方法二:使用内置函数tr计算字符串中特定字符的数量。在这里,我们将空格作为特定字符。
use strict;use warnings;my $str = "Hello world!";my $count = $str =~ tr/ //;print "空格数量:$count\n";无论是使用正则表达式还是使用tr函数,都可以得到字符串中空格的数量。

