Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

How do I reset an array?

by Jaspersan (Beadle)
on May 05, 2002 at 22:00 UTC ( #164176=perlquestion: print w/replies, xml ) Need Help??

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 <>
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";


    (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


        (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;

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://164176]
Approved by samtregar
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (10)
As of 2022-05-27 15:42 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (96 votes). Check out past polls.