Try this (working from your code as much as possible):
#!/usr/bin/perl -w
use strict;
sub solve
# solves any given function
{
my ($funct) = @_;
return "f(3) = " . $funct->(3);
}
sub foo
# a function to solve
{
my ($x) = @_;
return "This should print 6: " . ($x + 3);
}
print "Solving for foo:\n" . &solve(\&foo) . "\n";
# Solving for foo:
# f(3) = This should print 6: 6
__END__
The key difference is where you call the function inside solve(). The
construct "$funct->(3)" is what you want, de-referencing the code
reference and handing it the arg 3. You could do without the variable
$funct by just using "$_[0]->(3)" (no quotes).
The other changes I made were to take the print() statements out of the
subs, and instead returning the concatenated phrases. Otherwise, your
print statements will be output in the wrong order as the subs execute
from inside to out.
For general-purpose function solving, you might consider using eval(),
in case someone provides a function that blows up.
HTH
1;
On 5/19/04 Joseph Alotta wrote:
>#!/usr/bin/perl -w
>use strict;
>
>
>sub solve
># solves any given function
>{
> my ($funct) = @_;
>
> print "f(3) = ", @{$funct}(3), "\n";
>
>}
>
>sub foo
># a function to solve
>{
> my ($x) = @_;
>
> print "This should print 6", $x + 3, "\n";
>}
>
>
>print "Solving for foo", &solve(\&foo), "\n";
- Bruce
__bruce__van_allen__santa_cruz__ca__