Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: This should be easy: counting letters in a string

by inman (Curate)
on Jan 31, 2006 at 11:36 UTC ( #526714=note: print w/replies, xml ) Need Help??

in reply to This should be easy: counting letters in a string

The transliteration does not interpolate the variable as you expect in your sample. The following illustrates the use of eval.
use strict; use warnings; my @letters = qw (A B C D E F); my $string = "AFTYUBEWTWECRTUTYIYTDDDDRYJURTHJTREEEEEFGSDFF"; my $count; foreach my $a(@letters) { eval "\$count = \$string =~ tr/$a//"; print "$count\n"; }
You can also use a substitution in order to interpolate but avoid the eval.
$count = $string =~ s/$a//g;
Both methods change the string. A more flexible way to count the values would be to split the string and use a hash to store the values.
my %count; $count{$_}++ foreach split //, $string; print "$count{$_}\n" foreach (@letters);

Replies are listed 'Best First'.
Re^2: This should be easy: counting letters in a string
by Roy Johnson (Monsignor) on Jan 31, 2006 at 14:46 UTC
    Both methods change the string.
    No, tr/a// will not delete characters unless you specify the d modifier. Characters that are not replaced are left alone.

    And using a little trick to induce list context, you can use pattern matching to count the occurrences:

    my @letters = qw(A B C D E F); my $string = 'AFTYUBEWTWECRTUTYIYTDDDDRYJURTHJTREEEEEFGSDFF'; my @counts; for (0..$#letters) { $counts[$_] = () = $string =~ /$letters[$_]/g; } print "@counts\n";

    Caution: Contents may have been coded under pressure.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://526714]
[Corion]: I think there's always some Dell coupon around, at least I got one the last two times I bought a machine from them
[1nickt]: I have been an apostate in the Apple orchard for almost 15 years. But Dells are still high quality it seems, unlike Macs these days.
[1nickt]: And you can still configure the system at will, on the "Small Business" site.
[Corion]: 1nickt: I bought a 2015 XPS 13, which is a very nice and shiney (and somewhat overpriced) machine, but I think it's still better priced than an Apple machine. Now it just has to hold up 10 years like the old one did ;)

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2017-03-27 13:01 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (320 votes). Check out past polls.