in reply to Counting Characters

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

Replies are listed 'Best First'.
RE: RE: Counting Characters
by Ovid (Cardinal) on Jul 14, 2000 at 19:34 UTC
    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 :)