in reply to Re: Calling subroutine in a package from other perl sub.
in thread Calling subroutine in a package from other perl sub.
notation because (as perlsub mentions) you get an implicit argument list passed that you probably did not intend.&hello_world;
Also note that just calling something a module doesn't give you any protection if it doesn't use a package statement internally. When loading stuff from a file that doesn't use package you can always do it yourself by declaring a package and then using do to load it.
Note that the semantics here are slightly more generous than Perl's requirements of a module. I only warn if you don't get a defined value back. But the reason that I do this is that if it doesn't return something defined I cannot tell the difference between a system error caused executing the file and a system error caused by trying to read the file.# Loads a file into a package. sub load_lib { my $file = shift; my $pkg = shift; my $ret = eval "package $pkg; do '$file';"; if (not defined($ret)) { $@ and confess("Cannot parse '$file': $@"); $! and confess("Cannot load '$file': $!"); warn("Loading '$file' did not return a defined value"); } $ret; }
If that restriction bothers you, you can explicitly read the file's contents into a string with the package prepended and do your own eval of that. You may wish to look at the advice at the end of perlsyn on how to control the output of the error message though. (Put the package before the preprocessor message. There is a bug in 5.005 that causes a preprocessor message on the first line of an eval to be ignored. Besides which you need to do this to make the line-number you get be reasonable. :-)
Note that none of these solutions will help much if you have a script that does an exit somewhere. There are ways to override that, but if you are getting to this kind of detail, you probably wanted to make stuff into a module. :-)
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re (tilly) 2: Calling subroutine in a package from other perl sub.
by zzspectrez (Hermit) on Jan 17, 2001 at 06:13 UTC | |
by tilly (Archbishop) on Jan 17, 2001 at 07:48 UTC | |
by zzspectrez (Hermit) on Jan 17, 2001 at 11:33 UTC | |
by tilly (Archbishop) on Jan 17, 2001 at 17:20 UTC | |
by tye (Sage) on Jan 17, 2001 at 10:11 UTC | |
by zzspectrez (Hermit) on Jan 17, 2001 at 11:20 UTC | |
by tye (Sage) on Jan 17, 2001 at 22:19 UTC |