I find a number of times, that I've wanted to make some code that certain OSes would have better implementations of than others, or just plain implement in a different way.
There's some existing examples of code that does this; File::Spec comes
to mind. It chooses a specific subclass at runtime, based on the OS
choice ($^O), or falling back on a list of decreasing specificness if
that isn't found. Another example here would be a Linux-specific
subclass of File::Tail that can use Inotify rather than polling for
stat(). I've had further thoughts on things like /proc-scraping, network
interface information, etc...
What all these have in common is that $^O is used as a key to build a
list of possible module names, and the code then tries to load and use
the first one in the list it finds. Perhaps in cases like File::Tail
where the OS-specific class is simply more optimal, this could be an
optional installation later on.
I'd like to write a small module for automatically doing this sort of
magic; I'm just in short of a name for it. I feel it ought to be
Class-y; something like
Class::OSMagic
Class::OSSpecific
Class::MagicOS
Class::SystemSpecific
Class::ForSystem
As a brief example of code, consider the following hack on File::Tail.
Two-line change to File/Tail.pm:
use Class::OSMagic;
# Rename constructor
sub __new
{
...
}
The 'use' line would automatically import a 'sub new' into the caller,
which just does something like
sub new
{
Class::OSMagic::find_best_subclass( shift )->__new( @_ );
}
The user of File::Tail need not know the difference; the normal
my $tailer = File::Tail->new( $path );
constructor is unaffected.
If one day someone writes an Inotify-aware Linux extension, all they
have to do is provide
sub File::Tail::linux; # note lowercase, to match $^O
use Linux::Inotify;
sub __new
{
...
}
Now, any code that tries to use File::Tail objects on a Linux machine
will automatically find this subclass if it is installed.
There's a suggestion that the word 'magic' should be avoided - other
ideas on the name?
--
Paul "LeoNerd" Evans
[email protected] | CPAN ID: PEVANS
signature.asc
Description: Digital signature
