Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

perl

I am trying to figure out how to count any and all non-whitespace characters in a string such that in the example below I would get an output of 4.

my $str = 'A b C $'; 

my $cnt =~ /\S/g;  

print "Char Count: $cnt\n";

This Is there a Perl shortcut to count the number of matches in a string? does not answer my question.

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

Someone keeps wanting to say that this question is a duplicate of this question: Is there a Perl shortcut to count the number of matches in a string?

However, the other question references how to match a specific character, in their case I believe it's a dot. I looked at many other other examples that seek to match a specific character and could not get them to work to match all characters except whitespace.

This does not answer my question.

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

This question: What do \S, \W, \D stand for in regex? merely defines various Perl wildcard operators--one of which (the \S operator) I attempted to employ in my original question to no avail. It does not however demonstrate how one actually employs one of those operators in order to obtain the count of all non-whitespace characters in a string.

like image 996
gatorreina Avatar asked Nov 16 '25 09:11

gatorreina


1 Answers

From 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.

You can also query the Perl documentation from your command line:

perldoc -q count

use warnings;
use strict;

my $str = 'A b C $'; 
my $cnt = () = $str =~ /\S/g;
print "Char Count: $cnt\n";
like image 195
toolic Avatar answered Nov 19 '25 00:11

toolic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!