Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re^2: Redefine package subroutines

by tobyink (Abbot)
on Dec 19, 2012 at 12:15 UTC ( #1009552=note: print w/replies, xml ) Need Help??

in reply to Re: Redefine package subroutines
in thread Redefine package subroutines

OK, let's have a guess at the kind of thing you're doing. It probably differs in the details.

You have a script that needs to process a large directory tree; perhaps to perform backups or some other automated process. Some directories contain large text log files, which should be compressed before backing up, and once they're backed up they're never going to be modified so this knowledge allows us to shortcut a lot of processing. Other directories contain just images; these need to be backed up by uploading them to Flickr. And so on.

The way I'd approach this might be to keep a set of modules like this:

{ package Backup::General; sub backup_file { my ($class, $file) = @_; ... } sub backup_dir { my ($class, $dir) = @_; opendir my $d, $dir; while (readdir $d) { next if /^\./ or -d; $class->backup_file($_); } } ... } { package Backup::ImageDir; use parent 'Backup::General'; sub backup_file { my ($class, $file) = @_; $class->upload_flickr($file) if $file =~ /\.jpeg$/i; $class->SUPER::backup_file($file) } sub upload_flickr { ... } ...; } { package Backup::LogDir; use parent 'Backup::General'; sub backup_dir {...} ... }

Then each directory being backed up could contain a file backup.ini which looked something like this:

backup_class = "Backup::ImageDir"

My backup script would walk through the directories and for each:

use Config::Tiny; use Module::Runtime qw(use_package); my $config = Config::Tiny->read("$dir/backup.ini"); my $class = $config->{_}{backup_class} || 'Backup::General'; use_package($class)->backup_dir($dir);

That way, each directory decides for itself what module will handle its backups. There's no central list of backup modules; no limit to the number of different modules to choose from; the modules are loaded on demand as required.

This seems to be the sort of thing you want; some sort of general behaviour which can be overridden locally based on factors determined at runtime.

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1009552]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2017-07-21 13:43 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (323 votes). Check out past polls.