List::Util::max doesn't return index of the maximal element and works only on numeric scalars. So you have to help yourselvs.
use strict;
use warnings;
my @array = (
{ clothing => "Trouser", price => 40, Quantity => 2 },
{ clothing => "Socks", price => 5, Quantity => 12 },
);
my $maxi = 0;
for my $i ( 1 .. $#array ) {
$maxi = $i if $array[$i]{price} > $array[$maxi]{price};
}
$array[$maxi]{price} *= 2;
for my $rec ($array[$maxi]) {
print qq/{ ${\(join ', ', map "$_ => $rec->{$_}", sort keys %$rec)} }\n/;
}
If you are looking for more comfort and weird new syntax.
use strict;
use warnings;
use Carp;
my @array = (
{ clothing => "Trouser", price => 40, Quantity => 2 },
{ clothing => "Socks", price => 5, Quantity => 12 },
);
sub maxi (@) {
croak "Empty array" unless @_;
my $maxi = 0;
for my $i ( 1 .. $#_ ) {
$maxi = $i if $_[$i] > $_[$maxi];
}
return $maxi;
}
my $maxi = maxi map $_->{price}, @array;
print $maxi, "\n";
$array[$maxi]{price} *= 2;
for my $rec ( $array[$maxi] ) {
print qq/{ ${\(join ', ', map "$_ => $rec->{$_}", sort keys %$rec)} }\n/;
}
And finally you can use List::Util::max as with map and grep because all your array members are pointers to an anonymous hash so you can modify its content unless you want change them to some other type.
use strict;
use warnings;
use List::Util qw(max);
my @array = (
{ clothing => "Trouser", price => 40, Quantity => 2 },
{ clothing => "Socks", price => 5, Quantity => 12 },
{ clothing => "Shirt", price => 40, Quantity => 1 },
{ clothing => "Hat", price => 10, Quantity => 3 },
);
sub format_item {
my $item = shift;
local $" = ', '; # " for broken syntax highliter
return qq({ @{[map "$_ => $item->{$_}", sort keys %$item]} });
}
my $maxprice = max map $_->{price}, @array;
my @maxs = grep $_->{price} == $maxprice, @array;
# double prices
$_->{price} *= 2 for @maxs;
print format_item($_), "\n" for @maxs;
# if you are interested in the only one
my ($max_item) = @maxs;
print format_item($max_item), "\n";
List::Util::maxdoesn't return index but value itself.List::Util::maxworks on list of numbers, not bigger data structures. How do you compare your values? Are "Trousers" > "Socks" (because40 > 5) or other way round (because12 > 2).