in reply to How do I test the validity of a CODE reference?

You don't need eval and you can just inspect the main namespace for whether a subroutine of that name is defined:

use strict; use Data::Dumper; sub foo { print "foo\n"; } for my $subname (@ARGV) { my $glob = $::{$subname}; warn defined $glob ? "'*$subname' exists" : "'*$subname' not found"; if ($glob) { my $sub = *{$glob}{CODE}; warn defined $sub ? "'$subname' exists" : "'$subname' not found"; &$sub if $sub }; }

Replies are listed 'Best First'.
Re^2: How do I test the validity of a CODE reference?
by tinita (Parson) on Aug 10, 2008 at 12:57 UTC
    couldn't you just do
    if ( my $sub = main->can($subname) ) { $sub->(...) }
    ?
      Not quite. can is meant for methods, so it obeys inheritance.
Re^2: How do I test the validity of a CODE reference?
by pilap (Initiate) on Aug 08, 2008 at 17:33 UTC
    The reason I decided to use eval is that the user can put the required code in a package, and I don't need to know anything about it as long as he uses the fully qualified name as the subroutine name.

    Out of curiosity, how would you examine the symbol table for a package whose name you get from a variable? I'm not very comfortable with the syntax for typeglobs and Perl symbol tables...

      You can inspect any package, as the symbols for My::Package live in the %My::Package:: hash. The easiest way to get at those hashes is via soft references:

      use strict; use Data::Dumper; my $package = 'Data::Dumper'; # just as an example { no strict 'refs'; # we're using strings as symbols. Nasty, but con +venient warn Dumper \%{ "$package\::" }; };