tags:

views:

139

answers:

2

What if I have a string that consists of tuples in brackets and I would like to get the maximum value out of the tuple in Perl? Example:

Input: [everyday,32][hoho,16][toodledum,128][echigo,4]

Output: 128

+2  A: 

For the input provided:

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

Use ([^\]]+) instead of (\d+) if the values might be floating point values.

mobrule
I'd suggest always declaring an iterator variable -- i.e. foreach my $value ($input ....) -- rather than depending on $_, as it can sometimes change underneath you in unexpected ways. Likely not in this case, but it's a good habit to get into.
Ether
+5  A: 

If you want all of the data, you could put it into a hash first.

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 that number, you could then use a grep

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

If you really only need the max value:

use List::Util qw'max';
print max $str =~ /\[[^,]+,([^\]]+)\]/g;
Brad Gilbert
What do the carrot signs mean?
biznez
Normally [] says to match any one of the characters in between the brackets (e.g. a[bc]d would match abd, acd but not abcd). The '^' negates it, so that a[^bc]d would match aed, but not abd.
Joe Casadonte