vinoth.ree has asked for the wisdom of the Perl Monks concerning the following question:

my @array=('data1','data2'); my @array1=('data1','data2'); my ($i,$k); $i=7; $k=7; while($i){ $array [++$#array] = 'ree'; $i--; print "@array"; } while($k){ push(@array1,'ree'); $k--; print "@array1"; }

Are these two while loop are doing the same functionality ? What may be the difference?

Replies are listed 'Best First'.
Re: Alternative for push
by BrowserUk (Patriarch) on Mar 27, 2009 at 06:12 UTC
Re: Alternative for push
by chromatic (Archbishop) on Mar 27, 2009 at 05:59 UTC
    What may be the difference?

    The push approach is much easier to read.

Re: Alternative for push
by CountZero (Bishop) on Mar 27, 2009 at 07:13 UTC
    push (and its brethren pop, shift and unshift) take care of the indices themselves, so you don't have to worry about them.

    It is the same as with a for or a while loop: you can write that as a combination of control-variables, if ... then ... else tests and goto statements, but why would you want to do that?

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Alternative for push
by GrandFather (Saint) on Mar 27, 2009 at 10:18 UTC

    Better is:

    use strict; use warnings; my @array= qw(data1 data2); for (1 .. 7){ push @array, 'ree'; print "@array\n"; }

    although if the print is for diagnostic purposes then:

    my @array= (qw(data1 data2), ('ree') x 7); print "@array\n";

    is better still.


    True laziness is hard work
Re: Alternative for push
by cdarke (Prior) on Mar 27, 2009 at 12:51 UTC
    There are many alternative ways of adding an element onto the end of an array, none of which are as easy to read as push, although that is, of course, subjective. Many are considerably slower than push and some are just plain daft:
    push(@array, 'ree'); $array[$#array+1] = 'ree'; $array[@array] = 'ree'; splice(@array,@array,0,'ree'); @array=(@array,'ree');
    I'm fairly sure there are a couple more.
Re: Alternative for push
by Anonymous Monk on Mar 27, 2009 at 04:44 UTC
    Try this instead
    #!/usr/bin/perl -- use strict; use warnings; my @array=('data1','data2'); my @array1=('data1','data2'); my ($i,$k); $i=7; $k=7; while($i){ $array [++$#array] = 'ree'; $i--; print "@array\n"; } while($k){ push(@array1,'ree'); $k--; print "@array1\n"; } __END__