koleti has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,
I have a string like this
$string = 1,3,5,7,9,1,3,4,5,6,2,1,5,6,7,9
how can i know the no. of times each number is repeated
  • Comment on how to count the no of repeats in a string

Replies are listed 'Best First'.
Re: how to count the no of repeats in a string
by Fletch (Bishop) on Nov 13, 2007 at 19:14 UTC
Re: how to count the no of repeats in a string
by ikegami (Patriarch) on Nov 13, 2007 at 19:21 UTC

    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

      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).

Re: how to count the no of repeats in a string (Statistics::Frequency)
by lodin (Hermit) on Nov 14, 2007 at 00:55 UTC

    You can use the CPAN module Statistics::Frequency.

    use Statistics::Frequency; my $string = '1,3,5,7,9,1,3,4,5,6,2,1,5,6,7,9'; my %count = Statistics::Frequency::->new(split /,/, $string)->frequenc +ies; print "$_: $count{$_}\n" for sort keys %count; __END__ 1: 3 2: 1 3: 2 4: 1 5: 3 6: 2 7: 2 9: 2

    lodin

Re: how to count the no of repeats in a string
by toolic (Bishop) on Nov 13, 2007 at 19:21 UTC
    Here's one way:
    #!/usr/bin/env perl use warnings; use strict; use Data::Dumper; my $string = '1,3,5,7,9,1,3,4,5,6,2,1,5,6,7,9'; my @numbers = sort split /,/, $string; my %seen; for (@numbers) { if ($seen{$_}) { $seen{$_} += 1; } else { $seen{$_} = 1; } } print "@numbers\n"; print Dumper(\%seen);
      if ($seen{$_}) { $seen{$_} += 1; } else { $seen{$_} = 1; }
      can be simplified to
      $seen{$_}++;

      Your sort is also useless since hashes are unordered.