Hi

This may seem pity stupid but I am somehow stuck in this:
I have got a file containing years like this :

1913
1913
1917
1917
1917
1917
1917
1955
1955

now this is just a part of a file containing almost 50000 years.

What I want to do is :
count how many times a single year appears for the above sample, so in this case my output should have been something like this:
year count
1913 2
1917 5
1955 2

I have written a code but since it' not working it's pointless to post it here. still can anybody help me out with this.

Thanks
Aj

Recommended Answers

All 2 Replies

#!/usr/bin/perl
use strict;
use warnings;
my %years; #Hash to save year as key, count as value
while (<DATA>){
    chomp;
    $years{$_}++;
}
printf "%-10s %s\n",'year', 'count';
foreach (sort keys %years){
    printf "%-10s %d\n",$_, $years{$_};
}
__DATA__
1913
1913
1917
1917
1917
1917
1917
1955
1955

Thanks a lot..it solves the problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.