sly
sly

Reputation: 1780

how to get a maximum of a transformed array

Newbie alert. The following:

use List::Util qw(max);
use List::MoreUtils qw(apply);

my @list = ( 
        { 'name' => 'foo' , 'value' => 3 } , 
        { 'name' => 'bar' , 'value' => 31 } , 
        { 'name' => 'longname' , 'value' => -33 } , 
        { 'name' => 'grill' , 'value' => 333 } , 
        );

 print max apply { length $_->{name} } @list;

Outputs,

HASH(0x2e47c28)

Instead of 8.

What am I doing wrong?

Upvotes: 3

Views: 63

Answers (2)

Matt Jacob
Matt Jacob

Reputation: 6553

You don't need apply in this case because length doesn't modify the list items:

print max map { length $_->{name} } @list;

Upvotes: 4

user3967089
user3967089

Reputation:

It's not terribly clear from the List::MoreUtils documentation, but you have to assign to $_ in the code block to get the value to propagate out. So change the code block to { $_ = length $_->{name} } and it works.

Upvotes: 2

Related Questions