Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Counting Characters

by NeverMore (Acolyte)
on Jul 14, 2000 at 09:03 UTC ( #22508=perlquestion: print w/ replies, xml ) 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

Comment on Counting Characters
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 $_.
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

    - Ozymandias

    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;
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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.
(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;
    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;
      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;
      Or you can use this beauty (no, I'm not serious):
      $string = "This is a test\nMore Test"; $len = (grep /./s, (@chars = split //, $string));
      No, I don't suggest using them. I just had to toss it out because no one else had mentioned it :)
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;
    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...

      - Ozymandias

(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"; }
    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
    J. J. Horner
    Linux, Perl, Apache, Stronghold, Unix
    jhorner@knoxlug.org http://www.knoxlug.org/
    
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
RE: Counting Characters
by jlistf (Monk) on Jul 15, 2000 at 00:51 UTC
    $string = "teststring"; sprintf "%s%n", $string, $len; print "$len";
    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
      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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://22508]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2014-08-01 07:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (257 votes), past polls