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

Hi Monks!

I need to get details on all the elements of an array, like listing all the elements in the array and how many times it shows.
Here is what I have so far, any help will be great!

#!/usr/bin/perl use strict; use CGI qw/:standard/; use CGI::Carp qw(fatalsToBrowser); print header(); #######test 1 my @dates = qw(02/01/2009 01/31/2009 01/01/2009 01/31/2009 02/20/2009 02/20/2009 02/20/2009 02/20/2009 02/01/2009 ); my %count = (); my $c=0; foreach my $date (@dates) { $c++; $count{$date}++; print "<font size=1>$c</font> - $count{$date} - $date<br>\n"; }

My goal will be to have some thing like this at the end:
4 times 02/20/2009 2 times 02/01/2009 2 times 01/31/2009 1 times 01/01/2009

Thanks for the help!

Replies are listed 'Best First'.
Re: Print about all elements of the array.
by GrandFather (Saint) on Feb 24, 2009 at 04:00 UTC
    ... my %count; $count{$_}++ for @dates; print "$count{$_} times $_\n" for sort {$count{$b} <=> $count{$a}} key +s %count;

    Prints:

    Content-Type: text/html; charset=ISO-8859-1 4 times 02/20/2009 2 times 02/01/2009 2 times 01/31/2009 1 times 01/01/2009

    True laziness is hard work
Re: Print about all elements of the array.
by hbm (Hermit) on Feb 24, 2009 at 03:42 UTC

    How about this:

    use warnings; use strict; my @dates = qw(02/01/2009 01/31/2009 01/01/2009 01/31/2009 02/20/2009 02/20/2009 02/20/2009 02/20/2009 02/01/2009 ); my %dates; $dates{$_}++ for @dates; print map { "$dates{$_} times $_\n" } sort { $dates{$b} <=> $dates{$a} } keys %dates;
      What about this one:

      my @ndates = qw( 02/01/2009 01/31/2009 01/01/2009 01/31/2009 02/20/2009 02/20/2009 02/20/2009 02/20/2009 02/01/2009 ); my %counts = (); for (@ndates) { $counts{$_}++; } foreach my $keys (sort keys %counts) { print "\n\n$counts{$keys}= $keys\n"; }
Re: Print about all elements of the array.
by apl (Monsignor) on Feb 24, 2009 at 13:35 UTC
    What happened when you ran it? What did you do to try to fix it?
      The ideas here was very helpful, its all set, thank you all!