Combining key value pairs from parentheses in Perl

What if I have a string of parenthesized tuples and I would like to get the maximum value from the tuple in Perl? Example:

Entrance: [every day, 32] [hoho, 16] [toodledum, 128] [echigo, 4]

Output: 128

+2


source to share


2 answers


If you need all the data, you can first transfer it to a hash.

my %data = $str =~ /\[([^,]+),([^\]]+)\]/g;
use List::Util qw'max';
my($max) = max(values %data);
print "max: $max\n";

      

If you want to know which key (s) have this number, you can use grep



print "key: $_\n" for grep { $data{$_} == $max } keys %data;

      

If you really only want the maximum value:

use List::Util qw'max';
print max $str =~ /\[[^,]+,([^\]]+)\]/g;

      

+5


source


For the entered input:

$input = "[everyday,32][hoho,16][toodledum,128][echigo:4]";
$max = -Inf;
foreach ($input =~ /\[\w+,(\d+)\]/g) {
  $max = $_ if $max < $_;
}
print $max;

      



Use ([^\]]+)

instead (\d+)

if the values ​​can be floating point values.

+2


source







All Articles