Front page | perl.beginners |
Postings from June 2003
Re: Count Function?
Thread Previous
From:
Kevin Pfeiffer
Date:
June 27, 2003 07:03
Subject:
Re: Count Function?
Message ID:
1199436.DL60cW81Je@sputnik.tiros.net
Hi Paul,
In article <32148.193.134.254.145.1056721288.squirrel@wesley.pjcj.net>, Paul
Johnson wrote:
>
> Kevin Pfeiffer said:
[...]
>> 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//";
mumble, mumble... :-) I did try the example first, exactly has given in
perlop, but it didn't work. What I didn't try was the escape you use before
the string symbol.
> Read up on the two different types of eval, then you should be able to
> find out why you got 10.
Will do! It sounds like this might be a case of not having read far enough
(and I distantly remember having once read about two types of eval, but it
apparently hasn't sunken in, yet). Thanks for the tips.
-K
--
Kevin Pfeiffer
International University Bremen
Thread Previous