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

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions:
Counting characters

 



ronald29x
New User

Jul 27, 2005, 2:40 AM

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

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

best regards
Ronald


davorg
Thaumaturge / Moderator

Jul 27, 2005, 4:47 AM

Post #2 of 3 (2814 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.


Code
#!/usr/bin/perl 

use strict;
use warnings;

$_ = 'ABDGASJDKE';

my $letters = 'ADK';

print eval "tr/$letters//";


--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks


ronald29x
New User

Jul 27, 2005, 9:55 PM

Post #3 of 3 (2807 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
thanks


(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