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

Perl Monks, I'm trying to use anonymous subroutines, and I don't quite understand why this is not working. Here is a simplified code snippit:
#!/bin/perl use strict; my $testsub; my $subref = $tests $testsub = sub { print $_; }
This returns: Can't use string ("") as a subroutine ref while "strict refs" in use at ./test.pl line 5. Any ideas? <cr> -Craig

Replies are listed 'Best First'.
Re: Using references to subroutines
by broquaint (Abbot) on Apr 10, 2003 at 16:20 UTC
    Actually that code doesn't compile, but if you want to know about subroutine references and the use thereof see Re (tilly) 1: References quick reference. Here's some example code for anonymous sub usage e.g
    my $anonsub = sub { print "anonymous sub(@_)\n" }; $anonsub->("deref operator"); &$anonsub("sigil deref"); __output__ anonymous sub(deref operator) anonymous sub(sigil deref)
    See. perlsub for more info.
    HTH

    _________
    broquaint

Re: Using references to subroutines
by hardburn (Abbot) on Apr 10, 2003 at 16:17 UTC

    You're missing some semi-colons:

    my $subref = $tests; # Right here $testsub = sub { print $_; }; # And here

    You're assigning the anon sub to a variable, so the statement is being parsed as an expression that happens to contain a subroutine, not as a subroutine on its own.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated

Re: Using references to subroutines
by simon.proctor (Vicar) on Apr 10, 2003 at 17:36 UTC
    In addition to the comments made above, if you look at your code, you should hopefully see that if it did compile you aren't doing anything because you never dereference the subroutine reference. So the routine never gets called. Consider a slightly different version:
    use strict; my $testsub = sub { print $_[0]; }; &{$testsub}("hi");
    Here you can see that testsub becomes a reference to an anonymous subroutine. I then call it by dereferencing it and passing it a parameter to print. I could have used shift instead but wanted it to be a bit clearer for this example.

    HTH

    SP