[comp.lang.perl] problems with the defined

louie@sayshell.umd.edu (Louis A. Mamakos) (12/23/89)

Hello.  I'm having a bit of problem trying to use the defined() function.
What I'm trying to do is call a subroutine whose name is in a variable.  Before
doing such a thing, I'd like to use defined() to tell me if the subroutine
exists or not.

Here's a diddly test program:

#------------------------------------------------
do foo();
&foo();

$bar = "foo";
do $bar();
&$bar();

print "foo is defined\n" if defined(&foo);
print "foo() is defined\n" if defined(&foo());
print "foo via \$bar is defined\n" if defined(&$bar);
print "foo via \$bar() is defined\n" if defined(&$bar());

sub foo {
	print "Hello, in SUB\n";
}
#------------------------------------------------

When I run it, I get:

Hello, in SUB
Hello, in SUB
Hello, in SUB
Hello, in SUB
foo is defined
foo() is defined

Which means that I can invoke the subroutine in 4 different way, which I
expected, but I can't determine if the name of the suboutine exists or not.

Any suggestions?  I'm running the latest version of perl on a NeXT system.
Everything else seems to work ok.

	$Header: perly.c,v 3.0.1.3 89/12/21 20:15:41 lwall Locked $
	Patch level: 8

	Copyright (c) 1989, Larry Wall

	Perl may be copied only under the terms of the GNU General Public License,
	a copy of which can be found with the Perl 3.0 distribution kit.


louie

jv@mh.nl (Johan Vromans) (12/25/89)

RIn article <1989Dec22.212004.18316@haven.umd.edu> louie@sayshell.umd.edu (Louis A. Mamakos) writes:

Louis> What I'm trying to do is call a subroutine whose name is in a
Louis> variable.  Before doing such a thing, I'd like to use defined()
Louis> to tell me if the subroutine exists or not.
Louis> ...
Louis> Which means that I can invoke the subroutine in 4 different
Louis> way, which I expected, but I can't determine if the name of the
Louis> suboutine exists or not.

That's right. There is no way to determine if a subroutine has been
defined. Calling a undefined subroutine is always treated as a fatal error.
The best way to obtain what you want is to use 'eval' to call the
subroutine, and inspect $@ afterwards, e.g.

	$subname = "foobar";
	$result = eval ("&$subname()");
	if ( $@ ) {
	  # failed ...
	  print $@;
	}
	else {
	  # suceeded ...
	}

Happy hacking,

	Johan
--
Johan Vromans				       jv@mh.nl via internet backbones
Multihouse Automatisering bv		       uucp: ..!{uunet,hp4nl}!mh.nl!jv
Doesburgweg 7, 2803 PL Gouda, The Netherlands  phone/fax: +31 1820 62944/62500
------------------------ "Arms are made for hugging" -------------------------