Yes, the closure trick is clever, but I don't wonder which is faster. Aside from my assumption that it must be slower due to the function overhead in Perl, the obfuscation factor alone would cause me to eschew it. However, there's a more subtle problem at work that's going to kill many programmers. Since @_ aliases the argument list, the following two lines are equivalent:
my $r1 = sub { \@_ }->(@array); my $r2 = \@array;
What that means is that any processing on $r is going to affect @array. The following snippet will clarify.
use Data::Dumper; my @array = 1..10; my $aref = sub {\@_}->(@array); $_++ foreach @$aref; print Dumper \@array; my $r2 = \@array; print \@array,"\n",$r2;
The way to get around that with a closure is to do this:
my $r = sub {my @a = @_; \@a}->(@array);Clearly that's not going to be faster than simply copying the array.
Cheers,
Ovid
New address of my CGI Course.
Silence is Evil (feel free to copy and distribute widely - note copyright text)
In reply to Re: Re: Non-destructive array processing
by Ovid
in thread Non-destructive array processing
by Juerd
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |