in reply to Re: test for subroutine existence
in thread test for subroutine existence

Sorry, I probably wasn't clear enough in my original post (but that's why I added the code)...
I need to be able to test for a subroutine's existence, a subroutine who'se name is only available to me in a scalar -- so I can't very well use defined &my_sub (or can I?)

fuzzyping's right, eval does work pretty well, except that I end up actually executing the subroutine itself just to see if it's there -- I'd prefer not to actually run it at test time...

--twerq

Replies are listed 'Best First'.
Re: test for subroutine existence
by Abigail-II (Bishop) on Aug 12, 2002 at 14:32 UTC
    No eval needed.
    #!/usr/bin/perl use warnings 'all'; use strict; sub my_sub {1} foreach my $sub (qw /my_sub no_sub/) { print "$sub ", defined &$sub ? "exists\n" : "doesn't exist\n"; } __END__ my_sub exists no_sub doesn't exist
    Abigail
Re: Re: Re: test for subroutine existence
by twerq (Deacon) on Aug 12, 2002 at 14:27 UTC
    Okay, anyway -- now it seems pretty obvious:
    print "my_sub ", test_for_sub("my_sub") ? "exists\n" : "doesn't exist\ +n"; print "no_sub ", test_for_sub("no_sub") ? "exists\n" : "doesn't exist\ +n"; sub test_for_sub { my ($expr) = @_; return eval "defined &$expr"; } sub my_sub { 1; }


    --twerq