Update: How bizarre! I haven't been on Perlmonks all day, but I come here to make this weird post only to discover (after I post) a freakishly similar idea discussed today.
An interesting talk with a coworker about Smalltalk has inspired me to think about a new, rather curious module.
Often, when working on a project, I have many related packages. It can get awfully annoying to find this at the top of all of my code:
use Foo::Dates; use Foo::Customer; use Foo::Order; use Foo::Company; use Foo::Company::SalesReps; use Foo::Extremely::Long::Package::Name;
In Smalltalk, you just use (as in "make use of", not to be confused with Perl's keyword "use") the classes. In Java, there is at least a useful import keyword:
import Foo.*;I started to wonder why I can't do that in Perl. After talking to him about implementations, I took a snippet he wrote and came up with something like the following code:
sub HTML::TokeParser::Simple { my $module = (caller(0))[3]; undef *{$module}; eval "require $module"; if ($@) { require Carp; Carp::croak "No such module: $module"; } return $module; } package main; my $parser = HTML::TokeParser::Simple->new(\*DATA); __DATA__ <html> <head> ... more html
If you don't understand that code, what it does is create a function in the "HTML::TokeParser" namespace that undefs itself (so it won't be called more than once), uses the class in question and then returns the fully qualified name as a string.
So what if I were to create a module that did something like this:
use Class::WhenNeeded 'Foo'; my $customer = Foo::Customer->new($customer_id); my $order = Foo::Order->new;
In other words, we can skip the long lists of "use" and require declarations. I specifically mention "Class" in the package name as I expect that function oriented modules would be more difficult to manage due to exporting issues.
Another interface -- but more dangerous since it could have namespace collisions if you use subs with upper-case first letters:
use Class::WhenNeeded Foo => 'no_top_level'; my $customer = Customer->new($customer_id); my $order = Order->new;
Can anyone think of strong reasons why this would or would not be a good idea? I can see some problems with this, but it's an interesting idea.
Problems:
Cheers,
Ovid
New address of my CGI Course.
In reply to DWIM: autoloading classes by Ovid
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |