in reply to Altering Package Subs and Running In To Problems

Don't forget that the body of your package is run when it is use'd or require'd, so I do something like this:
#! start of my/db.pm package my::db; use Sybase::DBlib; sub new { return Sybase::DBlib->new(@_); } { package Sybase::DBlib; sub my_version_of_an_existing_method { # foo } }
So my end cgi scripts only 'use' the my::db module, and my::db->new returns a Sybase::DBlib object, but when you call $dbh->myVersionOfAnExistingMethod() you get my version instead of the built in version.

You can also add methods to the namespace that way as well.

Note that this is less clean if you are using a non-OO module, but by 'use'ing your module after the original one, the same effect will be had.

Replies are listed 'Best First'.
Re^2: Altering Package Subs and Running In To Problems
by mpeppler (Vicar) on Nov 11, 2004 at 19:49 UTC
    I dropped in here because I saw "Sybase", but:

    You should probably use @ISA and SUPER when you want to override methods from existing modules. Something like:

    package My::Db; use Sybase::DBlib; our @ISA=qw(Sybase::DBlib); # new() is only needed if you need to do additional # stuff - otherwise Sybase::DBlib's new() is called # automatically sub new { my $package = shift; my $dbh = $package::SUPER->new(@_); # do something with $dbh here .... return $dbh; } # Override dbnextrow() to allow ad-hoc processing sub dbnextrow { my $self = shift; # Call the real dbnextrow() my @row = $self::SUPER->dbnextrow(@_); # and now do some magic with @row before # returning it... .... return @row; }
    If you do it this way the whole system becomes extensible - you'll note that I never mention Sybase::DBlib in the package itself - only in the @ISA - and this lets perl decide at run-time what methods to call based on the inheritance tree.

    Michael

      That's true, but the author of Sybase::DBlib has said on a number of occasions that it is very hard to subclass for a number of reasons. This can be confirmed by trying!

      Apparently the latest version which either just got to CPAN or is just about to includes some changes which will make subclassing easier.

      So if all you want to do is, say, add a few methods - then something like I suggested is a good way to do it.

      In most situations your advice is, of course, correct.

        Err - I think you're confusing DBI and Sybase::DBlib...

        As I'm the author of Sybase::DBlib I suppose I should know :-)

        Michael