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

Ok, how do i reset an array to hold nothing? #-- @arr; #?? #-- #I make an array like so: @array=&getarray(); #and i loop through it, and append it to $blah: foreach $val (@array) { $blah=$blah.",".$val; } #but everytime i do this it appends the new array to the old $blah, i +tried $blah; ^jasper <jasper@wintermarket.org>
Updated by boo_radley : title change

Replies are listed 'Best First'.
(jeffa) Re: Arrays
by jeffa (Bishop) on May 05, 2002 at 22:17 UTC
    You can 'reset' an array like so:
    @arr = ();
    But you don't need to do that to get your code to work:
    use strict; # ALWAYS!!! my @array = &getarray(); my $blah; foreach my $val (@array) { $blah .= ",$val"; } print "$blah\n"; sub getarray { return ('a'..'d'); }
    Also, don't forget about join which will replace the for loop and concatention for you (and do a much better job anyway):
    print join(',', getarray()), "\n";

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
      my @array = &getarray();

      I tried it out and see that this works, but it doesn't seem to me that it should, since you appear to be storing a reference to the function in the array rather than the list of values returned by the function. Is this just a technique for deferring execution of getarray until the foreach my $val (@array) or is something else going on here?

        No deferrence going on here - &get_array() simple returns an array and not a reference (sub or array). Maybe this code will shed some light:
        use strict; use Data::Dumper; print Dumper get_array(); print Dumper get_array_ref(); print Dumper scalar get_something(); print Dumper get_something(); sub get_array { return ('a'..'d'); } sub get_array_ref { return [('a'..'d')]; } sub get_something { return wantarray ? ('a'..'d') : 'scalar'; }
        Also check out the difference between a list and an array

        jeffa

        L-LL-L--L-LL-L--L-LL-L--
        -R--R-RR-R--R-RR-R--R-RR
        B--B--B--B--B--B--B--B--
        H---H---H---H---H---H---
        (the triplet paradiddle with high-hat)
        
        That line just calls the sub and puts whatever is returned into @array. If you wanted to store a reference to a sub you would do this:
        my $subref = \&getarray;