Front page | perl.beginners |
Postings from June 2003
Re: Count Function?
Thread Previous
|
Thread Next
From:
Kevin Pfeiffer
Date:
June 27, 2003 06:29
Subject:
Re: Count Function?
Message ID:
15542679.ia8QitEfgZ@sputnik.tiros.net
In article <3EFC0AAF.5070001@kyocera-wireless.com>, Sudarshan Raghavan
wrote:
> Nelson Ray wrote:
>
>>Does anyone know of any sort of a function or method in perl that returns
>>the number of times a search string exists in a scalar. Say, how many
>>"a's"
>>are there in this sentence? I am able to write it myself, but I was
>>wondering if Perl had an inherent function for cleaner operation. I tried
>>looking through the list of functions at www.perldoc.com without success.
>>Thanks a lot for any help.
>>
>
> tr/// is what you need, perldoc perlop
> Assuming your string is in $_, the number of a's will be
> my $acnt = tr/a//;
Thanks to Sudarshan & Janek!
I found this as suggested...
# NOTE: (from perlop)
# Because the transliteration table is built at com
# pile time, neither the SEARCHLIST nor the REPLACE
# MENTLIST are subjected to double quote interpola
# tion. That means that if you want to use vari
# ables, you must use an eval():
#
# eval "tr/$oldlist/$newlist/";
# die $@ if $@;
#
# eval "tr/$oldlist/$newlist/, 1" or die $@;
But what I can't figure out (and have tried several variants) is how to get
the count when using a variable (ala' from inside an eval). This is the
closet I got:
my $sentence = "Here is my test sentence.\n";
my $letter = 'e';
my $count;
eval {$count = $sentence =~ tr/$letter//};
die $@ if $@;
print "The letter $letter appears $count times in the sentence...";
It produces "The letter e appears 10 times..." but the answer should be "6".
:-(
--
Kevin Pfeiffer
International University Bremen
Thread Previous
|
Thread Next