Just another Perl shrine PerlMonks

### Counting Characters

by NeverMore (Acolyte)
 on Jul 14, 2000 at 09:03 UTC Need Help??
NeverMore has asked for the wisdom of the Perl Monks concerning the following question:

How do I count the number of characters in a string? -NM

Replies are listed 'Best First'.
Re: Counting Characters
by btrott (Parson) on Jul 14, 2000 at 09:12 UTC
Would length work for you? :)
        length EXPR
length

Returns the length in characters of the value of EXPR.
If EXPR is omitted, returns length of $_. [download] Re: Counting Characters by Macphisto (Hermit) on Jul 14, 2000 at 17:23 UTC Generally the same way it is done in most languages. With the 'length' command. ex: #!/usr/bin/perl$text = "I like Pie";
$textLength = length($text);
print $textLength . "\n"; This returns 10. Simple as Pie! mmmm, pie..... The beatings will continue until morale raises. RE: Counting Characters by jlistf (Monk) on Jul 15, 2000 at 00:51 UTC $string = "teststring";
sprintf "%s%n", $string,$len;
print "$len"; [download] that is so evil. If you blew this one off because it looked like bad code, go check it out again. The key is the '%n'. perldoc -f sprintf [download] I'd have to give this the Most Obscure award. --Chris Update: Someone thought I was directing this to the author. Indeed not. You, the reader, should look at the code again. jlistf used a little known sprintf formatting technique to make this work. And it's just too cool to not file this tidbit away. e-mail jcwren (jjhorner) Counting Characters by jjhorner (Hermit) on Jul 14, 2000 at 21:20 UTC One way to count the occurrence of each character in a string: #!/usr/bin/perl -w use strict; #never, never leave home without it my %chars = (); my$string = "J. J. is cool!";
foreach my $character (split //,$string) {
$chars{$character}++;
}
print "Report:\n";
foreach my $key (keys %chars) { print "\t$key = $chars{$key}\n";
}
[download]
Yields:
[13:22:15 jhorner@gateway scripts]$./20000714-1.pl Report: = 3 ! = 1 o = 2 i = 1 J = 2 c = 1 s = 1 l = 1 . = 2 [download] J. J. Horner Linux, Perl, Apache, Stronghold, Unix jhorner@knoxlug.org http://www.knoxlug.org/  Re: Counting Characters (Ozymandias: Loop method) by Ozymandias (Hermit) on Jul 14, 2000 at 09:17 UTC There's probably a simpler way, but this will work: $count = "0"
while (/(.)/g) {
$count++ } print$count
[download]

Update: That's what I get for posting nodes after my bedtime. <G> Yes, I knew about "length", but btrott had already posted an answer using that; I decided to see if there was another way. Why? Because. And that's all the explanation I'm going to offer. <G>

Re: Counting Characters
by Anonymous Monk on Jul 14, 2000 at 11:36 UTC
You could reinvent the wheel,
but just use the one you got.
$d_length_o_var = length EXPR; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't let me do something like this again!!! by Ovid (Cardinal) on Jul 14, 2000 at 20:35 UTC And there's also the slightly obfuscated way to count characters :} $_ = "This is a test\nMore Test";
$len = map{/./s?$_:("red herring")}split//;
print $len; [download] Ooooooohhhhh..... stop me before I do something like that again!!!! * Ozymandias repeatedly smacks Ovid with a slightly oversize trout for his misdeeds Better? <G> This trouting brought to you from #perlmonks... (jcwren) RE: Counting Characters by jcwren (Prior) on Jul 14, 2000 at 18:10 UTC Or you could be really gross, and use a regexp: $_ = "This is a test\nMore Test";

$len = s/(.)/$1/gs;

print $len; [download] I'm convinced there is a way to do this with m//, but durned if I can figure it out. Ovid is the regexp guru around here (at least, I think so). --Chris e-mail jcwren Contrary to what jcwren says, I would hardly label myself a regex guru, but thanks for the compliment :) As far as I can tell, you can't use the match operator to return the length. The closest I came up with is a variation of Ozymandias' response: $string = "This is a test\nMore Test";
$len++ for ($string =~ /./sg);
print $len; [download] In the Perl Cookbook, it has a recipe for finding the nth occurence of a match, but that also uses a loop. If you could enumerate matches with a straight regex, you could construct a well-defined regex and skip the loop in the Cookbook. Believe me, I tried :) If any monks would like to tackle this, I'd love to be proven wrong (and I'm sure it would be something ridiculously simple). Update: And in my quest to come up with horribly unoptimized code: $_ = "This is a test\nMore Test";
$len = (split //); print$len;
[download]
Or you can use this beauty (no, I'm not serious):
$string = "This is a test\nMore Test";$len = (grep /./s, (@chars = split //, \$string));
[download]
No, I don't suggest using them. I just had to toss it out because no one else had mentioned it :)
RE: Counting Characters
by vroom (Pope) on Jul 14, 2000 at 21:34 UTC
If you're looking for the number of matches for a certain substring within a string you could look at the thread Counting Substrings in Strings. However depending on what you want one of the other solutions listed above might be simpler and better.

vroom | Tim Vroom | vroom@cs.hope.edu

Create A New User
Node Status?
node history
Node Type: perlquestion [id://22508]
Approved by root
help
Chatterbox?
 [thezip]: i don't get the command line "back" until I close VIM. No what I want to happen... [thezip]: I currently don't have access to CYGWIN, else I'd just do a tail -f on the logfile. [Corion]: thezip: If you want to open vim and can live with opening a second console window, use start "The results" vim.exe c:\path\to\logfile .log [thezip]: Ooops... I lied. I guess Cygwin is back. I'll just do a tail -f instead. Better. Sorry for the noise.

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (12)
As of 2017-03-27 18:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Should Pluto Get Its Planethood Back?

Results (321 votes). Check out past polls.