CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Regular Expressions:
Counting characters


New User

Jul 27, 2005, 2:40 AM

Post #1 of 3 (7803 views)
Counting characters Can't Post

what is the shortest way to count the sum of several characters in a word using regex?
ABDGASJDKE -> the word
A, D, K -> characters to count
5 -> the result

best regards

Thaumaturge / Moderator

Jul 27, 2005, 4:47 AM

Post #2 of 3 (7801 views)
Re: [ronald29x] Counting characters [In reply to] Can't Post

The quickest way is not to use a regex. The tr/// operator returns the number of matches it made.


use strict;
use warnings;


my $letters = 'ADK';

print eval "tr/$letters//";

Dave Cross, Perl Hacker, Trainer and Writer
Get more help at Perl Monks

New User

Jul 27, 2005, 9:55 PM

Post #3 of 3 (7794 views)
Re: [davorg] Counting characters [In reply to] Can't Post

thanks for the answer davorg.
now i want to count for more than 1 word and the input is from the stdin. the number of matches characters (n) is printed in the form of power 2 (2^n) (ex: 1, 2, 4, 8, etc ).
each one is separated by space.
actually i have make some code, but i need shorter code, if u have any idea how to make it shorter, please reply me soon, thank you.

my code:
print "2**($a=/[FTLD]/g) " while<>

after i read your reply:
print 2**(tr/'FTLD'//).$/ while<>

and i've changed it again:
print 2**y/FTLD//.$/ while<>

note: you can omit all the 'use' keyword, etc. just make it very very short

i want to make it 24 characters length of code or less

(This post was edited by ronald29x on Jul 28, 2005, 2:07 AM)


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives