eklerks has asked for the wisdom of the Perl Monks concerning the following question:
I have created an entity, which applies the elements to another entity, but the incantation follows the path of the black arts. I have to call upon another Perl Daemon to grant it life. Please show me my wrongs.
For the less spiritual enlighted:
It is a function, which applies the elements of an array to another function. Like the javascript apply. Here it is:
sub repeat { my $n = shift; my $x = shift; my $array = []; for($i = 0; $i < $n; $i++){ push @{$array}, $x; } return $array; } sub apply { my ($func, $args) = @_; my $size = @{$args}; my $app = repeat($size, '(shift @{$x})'); eval 'sub _apply { my $f = shift; my $x = shift; $f->(' . join +(',', @{$app}) . '); }'; return _apply(\&$func, $args); }
It does its job, but I have understood, that when I call eval another perl interpreter will be started. This is of course not very efficient. Is there a better way to get around this?
I thought about generating a couple of static functions like apply1 apply2 apply3 etc and put it in a package. But I find this offending too.
Example:
Thanks for your help!sub test { my $x = shift; my $y = shift; my $z = shift; print $x + $y + $z; } # output 6 apply(\&test, [1,2,3]);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Applying an array to a function
by BrowserUk (Patriarch) on May 29, 2010 at 23:21 UTC | |
by eklerks (Novice) on Jun 02, 2010 at 14:02 UTC | |
|
Re: Applying an array to a function
by choroba (Cardinal) on May 29, 2010 at 23:35 UTC | |
by ikegami (Patriarch) on May 31, 2010 at 03:19 UTC | |
by eklerks (Novice) on Jun 02, 2010 at 14:10 UTC |