Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

my $foo = \&sin; print $foo->(0.5), "\n";
gives me a Undefined subroutine &main::sin called at - line 2. What am I doing wrong?

Replies are listed 'Best First'.
Re: trouble taking reference of function
by samtregar (Abbot) on Mar 03, 2009 at 21:22 UTC
    Perl's builtins aren't generally made available as subs you can take a reference to. This works though:

    my $foo = sub { sin(@_) }; print $foo->(0.5), "\n";

    -sam

      Beware of prototypes when dealing with functions and named operators.
      $ perl -wle'print sin(0.5) == sub { sin(@_) }->(0.5) ?1:0' 0 $ perl -wle'print sin(0.5) == sub { sin($_[0]) }->(0.5) ?1:0' 1

      Update: Added code.

        Huh? Why does that happen?

        And you didn't even know bears could type.

Re: trouble taking reference of function
by ikegami (Patriarch) on Mar 03, 2009 at 21:23 UTC

    sin is actually an operator, not a function. You can wrap it in a sub.

    my $foo = sub { sin($_[0]) };
Re: trouble taking reference of function
by Fletch (Bishop) on Mar 03, 2009 at 22:05 UTC

    TMTOWTDI . . .

    use strict; use POSIX qw( sin ); my $s = \&sin; print $s->( 0.5 ), "\n";

    (Not necessarily a good way, but . . . :)

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.