in reply to Re: Can I add methods to an existing object?
in thread Can I add methods to an existing object?

Right, sorry..

I'm doing some Cat stuff and using Authen::Simple for authentication. My Cat instance has a Log::Dispatch logger which has methods like 'error','warning','debug' etc... Authen::Simple objects can take a logging object too, but it has to provide 'debug','info','warn' and 'error'. Log::Dispatch provides 'warning' but not 'warn'. To work around this, I made my own class which I called Log::Dispatch::Warn, which is a subclass of Log::Dispatch with a 'warn' sub which just calls 'warning'.

It seems kind of silly to create a whole module just to make an object call $self->warning(@_) if someone calls $object->warn($blah).

Replies are listed 'Best First'.
Re^3: Can I add methods to an existing object?
by linuxer (Curate) on Apr 02, 2009 at 23:55 UTC

    First, I thought of something like this:

    *Log::Dispatch::warn = *Log::Dispatch::warning;

    But I thought, that it doesn't look nice ;) so I changed it to:

    *Log::Dispatch::warn = \&Log::Dispatch::warning;

    But both threw warnings that Log::Dispatch::warn is "used only once: possible typo..."; And then, based upon the answers from morgon and mr_mischief I thought of

    sub Log::Dispatch::warn { my $self = shift; $self->warning(@_); }

    tested with:

    #!/usr/bin/perl -l use strict; use warnings; package foo; sub new { bless {}, shift(); } sub foo { my $self = shift; print "hello @_"; } package main; sub foo::bar { my ( $self ) = shift; $self->foo(@_); } *foo::baz = \&foo::foo; *foo::buzz = *foo::foo; my $o = foo->new(); $o->bar('world'); $o->baz('world'); $o->buzz('world'); __END__
      But both threw warnings that Log::Dispatch::warn is "used only once: possible typo...";
      And both are the Right Way to alias a function. Warnings are hints, not laws.
        And both are the Right Way to alias a function. Warnings are hints, not laws.

        I didn't write, that it's a wrong way. And I didn't write about warnings being laws. I like to get rid of warnings without writing no warnings;, so I mentioned another way which doesn't show a warning.

        Is it bad to look for ways to avoid warnings without writing no warnings;?

        sub foo::bar { my ( $self ) = shift; $self->foo(@_); }

        So, is that so much worse than aliasing the function?

        All in all, I I don't know how to handle your answer.
        What's your intention?
        Just information, that the aliasing was done right?
        Should I consider something else?

        Thanks in advance for your explanation.

Re^3: Can I add methods to an existing object?
by roubi (Hermit) on Apr 02, 2009 at 23:46 UTC
    It'd be interesting to hear from autarch himself why 'warn' wasn't added to the list of valid methods of Log::Dispatch when various other abbreviations like 'err' and 'crit' and 'emer' have been. Maybe he is just waiting to hear from someone like you? :)