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

    Why take the trouble of making the hash increment inside the pattern instead of in the loop? That kind of cheats the loop expression of its task. :-)

    my %counts; $counts{$1}++ while $string =~ /([^,]+)/g;

    lodin

      Too true! I had started with

      our %counts; "$string," =~ /([^,]*),(?{ $counts{$1}++ })/g;

      When that didn't work, I should have taken a step backwards, not a step forward (fixing the //g in scalar context).

        A step forward (for some definition of forward) could've been

        local our %counts; $string =~ /(?:^|,)([^,]*)(?:,|\z)(?{ $counts{$1}++ })(?!)/;
        if one really wants to do it the regex way. ;-)

        lodin