Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: test for subroutine existence

by Abigail-II (Bishop)
on Aug 12, 2002 at 13:59 UTC ( [id://189490]=note: print w/replies, xml ) Need Help??


in reply to test for subroutine existence

To see whether something is defined, you use the defined function:
#!/usr/bin/perl use warnings 'all'; use strict; sub my_sub {1} print "my_sub ", defined &my_sub ? "exists\n" : "doesn't exist\n"; print "no_sub ", defined &no_sub ? "exists\n" : "doesn't exist\n"; __END__ my_sub exists no_sub doesn't exist
Abigail

Replies are listed 'Best First'.
Re: Re: test for subroutine existence
by twerq (Deacon) on Aug 12, 2002 at 14:20 UTC
    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
      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
      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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://189490]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-07-16 19:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.