Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks.
Assume the following code:
use strict; use warnings; use List::Util qw(min max); my @AoA = ( ["nick","99"], ["john","88"], ["peter","77"], ["thomas","99"] ); my @numbers=(99, 88, 77, 88); my $max = max(@numbers);

I want to print both "nick" and "thomas", since they both have 99, how do I do that? I tried the following, but it prints them twice (obviously):
for my $i ( 0 .. $#AoA ) { for my $j ( 0 .. $#{$AoA[$i]} ) { if ($AoA[$i][1]==$max) { print $AoA[$i][0]."\n"; } } }

Replies are listed 'Best First'.
Re: help with an array of arrays
by Paladin (Vicar) on Sep 14, 2018 at 23:19 UTC
    Remove the inner loop. Since you already know the max number, you only need to loop through the outer array once, looking for ones that match the max number.
      Ah, good catch, thanks!
Re: help with an array of arrays
by LanX (Saint) on Sep 15, 2018 at 00:18 UTC
    TIMTOWTDI :)

    Since you like List::Util here a more functional approach.

    use strict; use warnings; use Data::Dump qw/pp dd/; use List::Util qw(min max); my @AoA = ( ["nick","99"], ["john","88"], ["peter","77"], ["thomas","99"] ); my @numbers=(99, 88, 77, 88); my $max = max(@numbers); pp map { $_->[0] } grep { $_->[1] == $max } @AoA;

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

      > a more functional approach

      my @numbers = map $_->[1], @AoA;
      ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
        better?

        use strict; use warnings; use Data::Dump qw/pp dd/; use List::Util qw(min max); use constant { name=>0, num=>1 }; my @AoA = ( ["nick","99"], ["john","88"], ["peter","77"], ["thomas","99"] ); my $max_num = max map { $_->[num] } @AoA; my @max_names = map { $_->[name] } grep { $_->[num] == $max_num } @AoA; pp @max_names;

        and for completeness another variant

        my @max_names = map { $_->[num] == $max_num ? $_->[name] : () } @AoA;

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery FootballPerl is like chess, only without the dice