How do I take a reference to `sin`?
Asked Answered
B

1

5

I can define a subroutine and take a reference to it like this

sub F { q(F here) }
$f = \&F;
print &$f           # prints “F here”

But how can I do the same with, e.g., sin?

$f = \&sin;
print &$f           # error: Undefined subroutine &main::sin called

That sounds as though I should be able to use \&MODULE::sin; evidently cos is not in main, but which module is it in? I do not see that documented anywhere.

Bedad answered 22/9, 2015 at 9:2 Comment(1)
You should avoid the use of the ampersand & whenever possible. You need to use it when taking a reference to a subroutine, like my $f = \&F, but you should call that reference with $f->()Byers
L
9

sin is not in your current package. You need to call it from the CORE:: namespace. CORE:: is where all the built-in functions reside. It is imported automatically.

my $f= \&CORE::sin;
print $f->(1);

Output:

0.841470984807897

Knowing about CORE::foo is mostly usefull if you want to call the original built-in after a function was overwritten.

use Time::HiRes 'time';

say time;
say CORE::time;

This outputs:

1442913293.20158
1442913293
Letaletch answered 22/9, 2015 at 9:11 Comment(2)
You know, I tried core and Core, but not CORE. I guess I knew this at some point :-).Bedad
@Bedad me too. But then I remembered. Note that there is also CORE::global:: to overwrite stuff.Letaletch

© 2022 - 2024 — McMap. All rights reserved.