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

I cannot figure out how to build an array of variable length

#incomplete sub wall { $count = 0; while ($count < $ pieces) { $count +=1; @stripe =(); } $wall_height = user input is 50 $stripe= user input is 11 $pieces=int($wall_height/$stripe); # pieces 50/11 = 4 #this the answer I want to come up with $stripe[0]= "11" $stripe[1]= "22" $stripe[2]= "33" $stripe[3]= "44"

next question: making a second set of stripes posted in direct replies by redmustang

Replies are listed 'Best First'.
Re: Building an array, "stripes on a wall"
by wind (Priest) on Jun 12, 2011 at 03:38 UTC
    my $wall_height = 50; my $stripe = 11; my @stripe = map {$_ * $stripe} (1..int($wall_height/$stripe)); print "@stripe"; =prints 11 22 33 44 =cut
Re: Building an array, "stripes on a wall"
by deep3101 (Acolyte) on Jun 12, 2011 at 06:43 UTC

    In Perl you don't need to explicitly define the array length as it dynamically allocates memory for the purpose on it's own. This is by far the best feature while working on arrays in Perl.

    You can use the push(@stripe,$pieces) with each time you do he calculation of $wall_height/$stripe. Or you even may use the unshift(@stripe,$pieces) function, whichever suites you more.

Re: Building an array, "stripes on a wall"
by Anonymous Monk on Jun 12, 2011 at 05:56 UTC
    See push, it adds elements to the end of an array
Re: Building an array, "stripes on a wall"
by PeterPeiGuo (Hermit) on Jun 12, 2011 at 07:02 UTC

    Perl array grows. Although many languages now support similar data structures, Perl was definitely the pioneer.

    Peter (Guo) Pei

Re: Building an array, "stripes on a wall"
by Not_a_Number (Prior) on Jun 12, 2011 at 12:44 UTC

    Just another way to do it:

    my $wall_height = shift || 50; my $stripe = shift || 11; my @stripes = grep { $_ % $stripe == 0 } 1 .. $wall_height; print "@stripes\n";

    If perchance you don't want a stripe painted on the very top course of your wall, just change

    1 .. $wall_height to 1 .. $wall_height - 1

Re: Building an array, "stripes on a wall"
by redmustang (Novice) on Jun 13, 2011 at 02:00 UTC
    Making stripe two is a success.
    I'm learning, this has been my first use of an array, map, and foreach (I got coping array and foreach on my own).
    @stripe_2=@stripe; foreach $srtipe_2 (@stripe_2) { $stripe_2=$stripe2-5; }
Re: Building an array, "stripes on a wall"
by redmustang (Novice) on Jun 12, 2011 at 18:15 UTC

    How would you create another set of stripes into @stripe_2 using the variable "my $stripe_2_size=5"

    I think this answer will be good. Most array documentation is not math like this

    results are

    $stripe_2[0]= "6" $stripe_2[0]= "17" $stripe_2[0]= "28" $stripe_2[0]= "39"