in reply to Calling a function that may not be there...

I suggest that you simply use:
if (defined &top) { ⊤ }
or
&top if defined ⊤
The defined operator returns true if &top is defined, false if there is no such function. This would appear to be exactly what you are looking for.

You should avoid the solutions based on can for two reasons: First, they will be less efficient, and second they may have additional semantics that you don't want.

The AUTOLOAD thing is utterly ridiculous. It's like squishing a bug with a pile driver.

Replies are listed 'Best First'.
Re: Re: Calling a function that may not be there...
by knobunc (Pilgrim) on Mar 27, 2001 at 19:51 UTC

    Edited becuase as Dominus pointed out, I was incorrect, and I wanted to disentangle my two points.

    If you simply wanted to call a bunch of subroutines in order you could be more clever:

    my @funcs = (); push @funcs, sub { print "middle\n"; }, sub { print "bottom\n"; }; push @funcs, some_subroutine_that_returns_sub_refs(); foreach my $sub (@funcs) { &$sub; }

    By passing the subroutine references around you can do lots of powerful things without depending on global subroutine names. It all depends on what you are really trying to do.

    -ben
      Said knobunc:
      That would work if there was a reference to the function involved. The original case had a simple subroutine definition.
      OK, you're wrong, and you obviously didn't try it, or even look in the manual.

      Says perlfunc:defined:

      You may also use defined(&func) to check whether subroutine &func has ever been defined.
      With all that code you wrote to show off, I would have thought you could also write the following three-line test to avoid embarassing yourself:
      sub a1 {} print "a1 is defined\n" if defined &a1; print "a2 is defined\n" if defined &a2;