develooper Front page | perl.beginners | Postings from June 2003

Re: Count Function?

Thread Previous | Thread Next
From:
Paul Johnson
Date:
June 27, 2003 06:41
Subject:
Re: Count Function?
Message ID:
32148.193.134.254.145.1056721288.squirrel@wesley.pjcj.net

Kevin Pfeiffer said:

> 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".
> :-(

You didn't follow the example - you changed the quotes for the eval.

You need this:

  eval "\$count = \$sentence =~ tr/$letter//";

or even better:

  $count = eval "\$sentence =~ tr/$letter//";

Read up on the two different types of eval, then you should be able to
find out why you got 10.

-- 
Paul Johnson - paul@pjcj.net
http://www.pjcj.net


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About