This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Dep::1; | |
use Dep::2; | |
... | |
use Dep::10; | |
my $thing = Dep::2->new; |
The program will load Deps 1..10 before executing Dep:2's constructor. However, with
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
my @deps; push "Dep::$_" for (1..10); | |
use Class::Autouse @deps; | |
my $thing = Dep::2->new; |
Only Dep::2 will be use-d before the instantiation of $thing.
This can be very useful in cases where an application's flow can take several different routes, and might not use all of its functionality in a single invocation. Padre, the Perl IDE, for example, makes extensive use of this module exactly for this reason.
But another cool feature of this library is its ':superloader' option. It allows you to import dependencies on the fly without explicitly saying so. For example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Class::Autouse qw(:superloader); | |
my $thing = Dep::2->new; |
Here, we don't predeclare any class in particular, we just use it. Notice that I said "class" and not "module"; this only works for object oriented libraries, ie., classes.
What's most useful about this is that it can be very convenient in cases where you don't know beforehand what classes you will be needing. In particular, I think this is a perfect addition to my Devel::REPL configuration file:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# in ~/.repl/repl.rc: | |
use Class::Autouse qw(:superloader); |
and then:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
brunov@dora:~$ re.pl | |
$_ my $thing = Foo->new; | |
$Foo1 = Foo=HASH(0xa77cb98) | |
$_ my $other = Bar->new; | |
$Bar1 = Bar=HASH(0xabc4eb8) |
Since I'm mostly doing exploration and debugging when using the REPL, correctness is not an issue, and not having to load things beforehand increases the whipuptitude and overall improves the coding experience.