http://qs321.pair.com?node_id=75258

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

  • Comment on Will recursive code update data in an array?

Replies are listed 'Best First'.
Re: Will recursive code update data in an array?
by Masem (Monsignor) on Apr 25, 2001 at 01:18 UTC
    If you pass the array as a reference, yes, the array elements can be modified. But if you pass the array directly, a copy will be made, and only the copies will be modified, the original array will not be changed:
    my @a = [ 1 .. 10 ]; by_value ( 5, @a ); # @a still is [1..10] by_ref( 5, \@a ); # @a will be [120, 240,... ] sub by_value { my ( $time, @a ) = @_; if ( $time == 0 ) return; foreach my $b ( @a ) { $b *= $time; } by_value( $time--, @a ); } sub by_ref { my ( $time, $a_ref ) = @_; if ( $time == 0 ) return; foreach my $b ( @$a_ref ) { $b *= $time; } by_ref( $time--, $a_ref ); }
Re: Will recursive code update data in an array?
by arturo (Vicar) on Apr 25, 2001 at 01:13 UTC

    If the array has wider scope than the subroutine, then yes. Unrealistic sample follows:

    my @array = (); my $counter =0; recurse(); sub recurse { push @array, $counter++; return if $counter > 25; recurse(); }