Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

how to do a reference to a func in Math::Trig

3 views
Skip to first unread message

Charles T. Smith

unread,
Jun 23, 2012, 2:47:52 AM6/23/12
to
Hi,

I'm experimenting with Math::Trig and would like to be able to pass the
function in as a parameter:

$f = $opts{f} || &sin;

...
$f($w);

Undefined subroutine &main::sin called at (eval
9)[/usr/lib/perl5/5.14.2/perl5db.pl:640] line 2.


I have also tried:

$f = &Math::Trig::sin;
Undefined subroutine &Math::Trig::sin called at (eval 10)...
$f = \&sin; # just delays the problem

etc.

Can anyone tell me how to take a reference to func in a module?

TIA
cts

Adam Russell

unread,
Jun 23, 2012, 9:27:11 PM6/23/12
to
Math::Trig does not define sin() or cos() as they are already defined
in core Perl.

Here is how you would do it with sin()
$f=sub{return sin($_[0])};
print &$f($x),"\n";

and here is an example of what you specifically asked for (a function
from Math::Trig)

use Math::Trig;
$f=sub{return Math::Trig::asin($_[0])};
$x=1;
print &$f($x),"\n";

Charles T. Smith

unread,
Jun 24, 2012, 6:49:17 AM6/24/12
to
On 06/24/12 03:27, Adam Russell wrote:
> Math::Trig does not define sin() or cos() as they are already defined
> in core Perl.
>
> Here is how you would do it with sin()
> $f=sub{return sin($_[0])};
> print &$f($x),"\n";
>
> and here is an example of what you specifically asked for (a function
> from Math::Trig)
>
> use Math::Trig;
> $f=sub{return Math::Trig::asin($_[0])};
> $x=1;
> print &$f($x),"\n";
>


Oh, that's cool, how you used an anonymous function to do that. I tried
that, too, but couldn't make it work.

But there's another answer that I got on the begi...@perl.com:

> The cos sub is defined in Math::Complex, which Math::Trig loads.
>
> Try this:
>
> use strict;
> use Math::Trig;
>
> my $cos = \&Math::Complex::cos;
> print $cos->(0);

Charles T. Smith

unread,
Jun 24, 2012, 6:52:40 AM6/24/12
to
Incidently, this is what I wrote back:

> Thank you, that was the clue I needed! This now works for me:
>
> ...
> $f = $opts{f} || "sin";
> ...
> $f = "Math::Complex::$f";
> ...
> print eval ($amplitude) * (&$f (2 * pi * $i/$n) + eval ($dc))."\n";
>
> and so I can use this, my "siggen" pgm with gnuplot:
>
> plot "<(./siggen -f cos -p 2 -n66 )" lc 1
>
> to get a nice curve.
>
> Unfortunately, though, I was only able to get it to work as symbolic reference. First I tried:
>
> $f = \&Math::Complex::$func;
>
> Scalar found where operator expected at ./siggen line 194, near "&Math::Complex::$func"
> (Missing operator before $func?)
> syntax error at ./siggen line 194, near "&Math::Complex::$func"
>
> I also tried:
>
> $f = eval (\&Math::Complex::$func)
>
> but that didn't help.
>
> But that's all unimportant, because my pgm works now,
> thank you.
>
> cts
0 new messages