Home > Net >  How to find the max and min values in a Hash using Perl
How to find the max and min values in a Hash using Perl

Time:07-23

I am trying to find a simple way to find the max and min values of a hash array using Perl. It seems I am getting the max value but not the min value.
Here is my code:

#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw(min max);

# defines TimeStamp => time which is coming from a csv file
my %timess = (
 'TimeStamp' => 127000.2323,
 'TimeStamp' => 124000.2323,
 'TimeStamp' => 125000.2323,
 'TimeStamp' => 128000.2323,
 'TimeStamp' => 129000.2323
);

foreach my $row (values %timess) {
    my $maxTime = max($row);
    my $minTime = min($row);
    printf("max: %d, min: %d\n", $maxTime, $minTime);
}

The output

max: 129000, min: 129000

I have tried different methods even posted in this link: Perl: find the max and min values in the array of hashes

Any feedback will be great!

CodePudding user response:

I solved this problem, thanks to @jhnc advice

#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw(min max);

# defines TimeStamp => time which is coming from a csv file
my %timess = (
 'TimeStamp' => [
     127000.2323,
     124000.2323,
     125000.2323,
     128000.2323,
     129000.2323
     ]
);

foreach my $row (keys %timess) {
    my $maxTime = max(@{$timess{$row}});
    my $minTime = min(@{$timess{$row}}); 
    printf("max: %d, min: %d\n", $maxTime, $minTime);
}

Output:

max: 129000, min: 124000

CodePudding user response:

use List::MoreUtils qw( minmax );

my ( $min, $max ) = minmax( $times{ TimeStamp } );
  •  Tags:  
  • perl
  • Related