Richard Lee wrote:
>
> John W. Krahn wrote:
>
>> Richard Lee wrote:
>>
>>> Can you please tell me how to shorten this?
>>>
>>> my @an = split(//);
>>> my @num = grep { $_ eq ':' } @an ;
>>>
>>> I was trying to see how many : occur in variable but didn't know how 
>>> to do it fast so i did it like above...
>>>
>>> I would like to see as many way different ways to get this done if 
>>> possible
>>>
>>>
>>> $var1 = root:x:123:/root:
>>>
>>> trying to see how many times : occurs in $var1..... and I could only 
>>> do it above way....
>>
>> my $count = $var1 =~ tr/://;
> 
> Talking about reinventing the wheel!!  thank you and I shall try this.. 
> as I have nver tried tr before.......... thank you!!

tr/// is in the long tradition of Unix misnomers. It is comparable to s///g, but
tr(anslates) characters in the first list to those in the second list, so

  $str =~ tr/;:/../;

would replace all colons and semicolons with full stops. It returns the number
of characters it has translated. However, if there is no character in the
corresponding position in the second list the character remains unchanged but
the count is still maintained, so

  $str =~ tr/://;

returns the number of colons found but leaves them untouched. Similarly

  $str =? tr/\t /_/;

translates all tabs to underscores, leaves spaces untouched, and returns the
total number of either tab or spaces found in the object string.

It is Perl idiom, and you should learn it.

(If you want to be even more obscure then y/// is a synonym for tr///)

HTH,

Rob

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to