in reply to Re: Re: Non-destructive array processing
in thread Non-destructive array processing

Since @_ aliases the argument list, the following two lines are equivalent:
my $r1 = sub { \@_ }->(@array); my $r2 = \@array;

No they're not :-)

The first is a reference to an array that has every element aliased to every element of @array.

The second is a reference to @array.

The "trick" wouldn't work otherwise, since changing $r2 will change @array. For example.

my @array = (1..10); my $r1 = sub { \@_ }->(@array); pop @$r1; print "unchanged @array\n"; my $r2 = \@array; pop @$r2; print "changed @array\n";

gives us

unchanged 1 2 3 4 5 6 7 8 9 10 changed 1 2 3 4 5 6 7 8 9

Replies are listed 'Best First'.
Re: Re: Re: Re: Non-destructive array processing
by demerphq (Chancellor) on Jan 21, 2003 at 13:17 UTC
    The first is a reference to an array that has every element aliased to every element of @array.

    Very very true. (I was going to say if it wasnt already said...) This has some devious implications. Consider the consequences of this:

    $\="\n"; my ($x,$y,$z)=(1,2,3); my $r=sub{ \@_ }->($x,$y,$z,$z,$y,$x); print $r->[0]; # 1 $r->[-1]=10; print $r->[0]; # 10
    So personally I wouldnt use this approach at all (for this anyway). Theres waaaay too much chance that somebody would come along and morph the code without understanding the deeper implications and then run around screaming about bizarre bugs.

    --- demerphq
    my friends call me, usually because I'm late....