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

Dear monks, If i have 10 arrays, how can i find out which is the biggest e.g. which has the most elements? many thanks

Replies are listed 'Best First'.
Re: finding the biggest array
by davido (Cardinal) on May 06, 2004 at 16:33 UTC
    That depends. Do you want to know the highest index of the biggest, do you want a reference to the biggest, or do you want to perform an action on the biggest. You would approach it slightly differently with each objective.

    Remember that evaluated in scalar context, an array gives its number of elements. Therefore, with my $count = @array; $count will contain the number of elements in @array. Check your 10 arrays that way and figure out which one is the biggest.


    Dave

Re: finding the biggest array
by fglock (Vicar) on May 06, 2004 at 16:45 UTC
    use strict; my @arrays = ( [ 1, 2, 3 ], [ 4, 5 ], [ 6, 7, 8, 9 ], [ ] ); my ( $biggest ) = sort { $#$b <=> $#$a } @arrays; print "biggest is @$biggest\n";

    Output:

    biggest is 6 7 8 9
Re: finding the biggest array
by pizza_milkshake (Monk) on May 06, 2004 at 16:59 UTC
    i believe what needs to be done is the sort references to arrays, because i believe (@a, @b, @c) will translate into one list of ($a[0] .. $a[$#a], $b[0] .. $b[$#b], $c[0] .. $c[$#c])
    #!perl -wl use strict; my ($x, $y, $z) = ([0..1], [0..2], [0..3]); my ($longest) = sort { $#$b <=> $#$a }($x, $y, $z); print "@$longest";

    perl -e"\$_=qq/nwdd\x7F^n\x7Flm{{llql0}qs\x14/;s/./chr(ord$&^30)/ge;print"

Re: finding the biggest array
by Anonymous Monk on May 06, 2004 at 20:51 UTC
    my @arr1 = qw( one two ); my @arr2 = qw( foo bar baz qux ); my @arr3 = qw( just another hacker ); print join( ', ', biggest_array(\@arr1, \@arr2, \@arr3) ); sub biggest_array { map { @$_ } ( sort { @$b <=> @$a } @_ )[0] }