Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

About using a function pointer/reference in Perl?

Status
Not open for further replies.
Oct 11, 2006
5
US
I'm trying to use Eric Boesch's library, Math::Integral::Romberg, for the integral of a Gaussian distribution from 0 to 1. However I have some problems about "a reference to the function to be integrated". In my code, I wrote

$area=integral(\&func, 0, 1);

to do the integration, which is suggested in the synopsis. To define my function (I start with a simple one), I wrote

sub func
{
my $x;
$x*2+5;
}

, which was intended to be f(x)=2x+5.

However, the integral results are not correct. Any ideas? Really need your help ... Could anyone please give me a Perl script example about how to write this function?

Thanks so much for your help.
 
I haven't used that module myself, but if you can post what you're getting as your output and what you're expecting to get, we might be able to help better.
 
I think the problem is in your function:

Code:
sub func
{
    my $x;
    $x*2+5;
}

What is $x? You declared it as an undefined variable with no value, then multiply it by 2 and added 5.

I looked at the source of the module, and it calls $f two times, one passing in $x1 and the other $x2, and that $f should return a value. Your function might be returning the value of $x*2+5, but it always looks nicer to explicitely return things.

Code:
sub func
{
    [COLOR=blue]# get $x from @_ (passed-in arguments)
    my $x = shift;[/color]
    return $x*2+5;
}

See if that helps. :)

-------------
Kirsle.net | Kirsle's Programs and Projects
 
woooow it works now! I tried
sub func
{
# get $x from @_ (passed-in arguments)
my $x = shift;
return $x*2+5;
}
and the result is correct now. Thanks sooo much - really lots of help and favor.

Thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top