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

Hi, i have list of top ten sites, but sometimes it screws up and sometimes shows 11, 12 even 13. say that they are stored in @topten... is there a 'perl' way to maintain 10 elements in that array? thanks.
  • Comment on Maintain a certain number of elements inside an array?

Replies are listed 'Best First'.
Re: Maintain a certain number of elements inside an array?
by tachyon (Chancellor) on Oct 23, 2001 at 22:49 UTC

    Here are a few different ways:

    @too_many = qw ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ); # use a slice @top_ten = @too_many[0..9]; print "@top_ten\n"; # or perhaps a push push @ten, $too_many[$_] for 0..9; print "@ten\n"; # or be a little obscure pop @too_many while @too_many > 10; print "@too_many\n";

    TIMTOWTDI cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: Maintain a certain number of elements inside an array?
by chipmunk (Parson) on Oct 23, 2001 at 23:58 UTC
    One more way to do it: splice @topten, 10; That lops off all the elements at index 10 and higher.
Re: Maintain a certain number of elements inside an array?
by tommyw (Hermit) on Oct 24, 2001 at 02:24 UTC

    I'm suprised it's not been mentioned. Simply:

    $#topten=9

Re: Maintain a certain number of elements inside an array?
by Fletch (Bishop) on Oct 23, 2001 at 22:51 UTC
    for( my $i = 0; $i <= 9; $i++ ) { do_whatever( $topten[ $i ] ); } # or foreach( @topten[ 0 .. 9 ] ) { do_whatever( $_ ); } # or @topten = @topten[ 0 .. 9 ]; do_whatever( $_ ) foreach @topten; # or $#topten = 9; do_whatever( $_ ) for @topten;
Re: Maintain a certain number of elements inside an array?
by joealba (Hermit) on Oct 23, 2001 at 22:58 UTC
Re: Maintain a certain number of elements inside an array?
by higle (Chaplain) on Oct 23, 2001 at 22:47 UTC
    Perhaps if you showed your code, we might be of more service...

    The only thing I can think of without your example source is a little something that irked me when I first started...

    Variables in Perl are, by default, "global" in a sense. In other languages, the scope of a variable is, by default, local to the subroutine or class or whatever is using the variable....

    So, if you don't re-initialize a variable each time a subroutine fires, it might still have residual values from a previous iteration of the subroutine, thus you get unpredictable array results, etceteras.

    That's about all I can offer, without seeing your code...

    --higle
Re: Maintain a certain number of elements inside an array?
by drewboy (Sexton) on Nov 03, 2001 at 03:17 UTC
    Thanks for all your help! The splice suggestion by tommyw did it for me. Ciao!