-1

I have a file in the following format

a1 1901 score1
a2 1901 score2
a3 1902 score3
a4 1902 score4
a5 1903 score6
a6 1903 score7

I want to create a hash of every year and the values in the first column corresponding to this year as an array (which means year as key of the hash and the values in first column as array of values). How to do this using perl..

1

2 Answers 2

1

You should read about autovivification:

#!perl

use strict;
use warnings;

use Data::Dumper; 

my %h;
while (my $line = <DATA>) {
  chomp $line;
  my ($val, $year) = split /\s+/, $line;

  push @{$h{$year}}, $val;
}

print Dumper \%h;
# $VAR1 = {                   
#          '1901' => [       
#                      'a1', 
#                      'a2'  
#                    ],      
#          '1902' => [       
#                      'a3', 
#                      'a4'  
#                    ],      
#          '1903' => [       
#                      'a5', 
#                      'a6'  
#                    ]       
#        };                  
__DATA__
a1 1901 score1
a2 1901 score2
a3 1902 score3
a4 1902 score4
a5 1903 score6
a6 1903 score7
Sign up to request clarification or add additional context in comments.

1 Comment

It wouldn't be much different without autovivification: push @{ $h{$year} //= {} }, $val;
0

So, the next step was to find the row corresponding to max score, I wrote something like this. This gets me per year wise what is the max score but I am unable to fetch the index of the calculated max so that I can use that to print the corresponding values in column 1. For example: if for the year 1901 score2 is max, then I want to print

a2 1901 score2

But with my current code I can only print

1901 score2

use strict;
use warnings;
use List::Util qw( min max );
use Data::Dumper;
my $file=shift;
open (DATA, $file);
my %h1;
my @tmp;
my $max_value;
my $a;
my $b;
while (my $line = <DATA>) {
  chomp $line;
  my ($val, $year, $score) = split /\s+/, $line;
  push @{$h1{$year}}, $val;
  push @{$h1{$year}}, $score;
}
foreach my $x (sort keys %h1)
{
        foreach (@{$h1{$x}})
        {
                if ($_=~/^[0-9]/)
                {
                        push @tmp, $_;
                }
$max_value= max @tmp;
        }
        print "$x\t$max_value\n";
}
print Dumper \%h1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.