Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re^3: Non-destructive array processing

by adrianh (Chancellor)
on Jan 20, 2003 at 22:51 UTC ( #228515=note: print w/ replies, xml ) Need Help??


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


Comment on Re^3: Non-destructive array processing
Select or Download Code
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....

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://228515]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2014-09-02 03:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (19 votes), past polls