Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

telling whether a function exists

Status
Not open for further replies.

fishiface

IS-IT--Management
Feb 24, 2003
687
GB
I have a modular app which loads one of many modules depending on circumstances. Each module implements and exports one or more of a set of functions.

My main app needs to run certain functions if they are available and take some default action otherwise. My first stab was
[tt] if ( exists $main::{somefunc} ) { # somefunc in symbol table
somefunc(); # possibly defined externally
} else {
defaultfunc(); # defined in this file
}[/tt]
but this fails, complaining about an attempt to run a non-existant [tt]somefunc()[/tt]. Perl seems to put a stub entry in the symbol table at compile time because [tt]somefunc()[/tt] has been mentioned. Using [tt]defined[/tt] instead of [tt]exists[/tt] does not help, although I don't understand why not.

Using a soft reference solves the problem:
[tt] if ( exists $main::{somefunc} ) {
&{'somefunc'}();
} else {
defaultfunc();
}[/tt]

I'd be interested in any comments as this is far from elegant!

Yours, "As soon as we started programming, we found to our surprise that it wasn't as
easy to get programs right as we had thought. Debugging had to be discovered.
I can remember the exact instant when I realized that a large part of my life
from then on was going to be spent in finding mistakes in my own programs."
--Maurice Wilk
 
Perhaps a more elegant solution would be to use AUTOLOAD:
Code:
sub AUTOLOAD {
  print "Could not find subroutine $AUTOLOAD. Using default\n";
  default($AUTOLOAD, @_);
}

sub default {
  print "Called default with @_\n";
}

foo("bar");
Hope this helps, Cheers Neil :)
 
Mmmm. That's prettier. Delving into the symbol table seemed like an ill-fitting sledgehammer, if you'll excuse the mixed metaphor ;-)

Many thanks, "As soon as we started programming, we found to our surprise that it wasn't as
easy to get programs right as we had thought. Debugging had to be discovered.
I can remember the exact instant when I realized that a large part of my life
from then on was going to be spent in finding mistakes in my own programs."
--Maurice Wilk
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top