in reply to Re: counting inside the loop
in thread counting inside the loop
my $count=($str2=~ tr/$t1//);
This will count how often the characters in $t1 are in $str2 ...
Unfortunately, the tr/// operator does not interpolate, but the s/// or, better yet, the m// operator can serve here:
>perl -wMstrict -le "my $s = 'foo bar fooo bar foooo bar'; my $cc = 'foz'; ;; my $count = ($s =~ tr/$cc//); print $count; ;; $count = '$c$c$' =~ tr/$cc//; print $count; ;; $count = $s =~ tr/foz//; print $count; ;; $count = $s =~ s{ ([$cc]) }{$1}xmsg; print $count; ;; $count =()= $s =~ m{ [$cc] }xmsg; print $count; ;; $count = $s =~ s{ [$cc] }{}xmsg; print $count; print qq{'$s'}; " 0 5 12 12 12 12 ' bar bar bar'
Note: There is no need for a capture group in the s/// expression if characters in the string can be counted 'destructively':
$count = $s =~ s{ [$cc] }{}xmsg;
Update: Added s/// and m// examples, discussion.
|
|---|