Bob Walton <> writes:
> Sherm Pendley wrote:
>
>> That will still only be once, because a subroutine is compiled only
>> once
>> no matter how many times it might be called. That includes zero times -
>> a subroutine that's never called is still compiled.
>
> Counterexample:
>
> #File junk552.pm:
> package junk552;
> sub import{
> print "import called:@_\n";
> }
> 1;
>
> #File junk552.pl:
> use junk552(a);
> use junk552(b);
>
> #Results of run:
> d:\junk>perl junk552.pl
> import called:junk552 a
> import called:junk552 b
I thought I'd left enough quotage to make the context clear, but I may have
oversnipped - sorry 'bout that.
Anyhow, we were discussing a single use() statement appearing in a subroutine
that's called many times. For instance:
sub foo {
use junk552(a);
}
The "use junk552(a);" is evaluated at compile-time, so it's called only once
no matter how many times you call foo() at run-time.
Your counter example doesn't negate that point, it simply illustrates something
entirely different - although a given module is only loaded and compiled once,
its import() subroutine may be called any number of times. If you really think
about it, it's obvious why this happens - how else could a package's symbols be
exported into more than one name space?
But as your example shows, that happens as a result of multiple use() state-
ments. It would not happen as a result of additional invocations of foo() in
the example above.
If you want to have a use() that's evaluated at run-time, you have to wrap it
in a string eval().
sub foo {
eval 'use junk552(a)';
}
One common use of this is to make the use of a module optional by checking for
its existence at run-time:
our $junk_exists;
sub check_junk {
$junk_exists = eval 'use junk552';
}
# ...later...
if ($junk_exists) {
my $foo = new junk552();
}
sherm--
--
Cocoa programming in Perl:
http://camelbones.sourceforge.net
Hire me! My resume:
http://www.dot-app.org