in reply to how to count the no of repeats in a string
If you're dealing with a known set of tokens (i.e. numbers), you could just search for each in turn.
my $string = '1,3,5,7,9,1,3,4,5,6,2,1,5,6,7,9'; for my $num (1..9) { my $count = () = ",$string," =~ /,$num(?=,)/g; print "$num\t$count\n"; }
1 3 2 1 3 2 4 1 5 3 6 2 7 2 8 0 9 2
The general solution of using a hash is probably better, though.
my $string = '1,3,5,7,9,1,3,4,5,6,2,1,5,6,7,9'; our %counts; my $x = "$string,"; 1 while $x =~ /([^,]*),(?{ $counts{$1}++ })/g; for my $num (sort { $a <=> $b } keys %counts) { print "$num\t$counts{$num}\n"; }
1 3 2 1 3 2 4 1 5 3 6 2 7 2 9 2
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: how to count the no of repeats in a string
by lodin (Hermit) on Nov 14, 2007 at 00:44 UTC | |
by ikegami (Patriarch) on Nov 14, 2007 at 02:30 UTC | |
by lodin (Hermit) on Nov 14, 2007 at 03:08 UTC |