in reply to Can I add methods to an existing object?

If you can accept that the method is added to the class (and not just to this one instance in the way you can have singleton-methods e.g. in Ruby) this is very simple as methods are just symbol-table entries just like any other sub.

Here an example that adds a new "bubba" method to a "Hubba"-class after an instance already has been created:

use strict;

package Hubba;

sub new {
 my($pck)=@_;

 bless {}, $pck;
}

# no bubba-method defined here

package main;

# create new instance
my $h = new Hubba;

# add entry to symbol-table
*Hubba::bubba = sub { print "bubba" };

# call new method via old instance
$h->bubba;

  • Comment on Re: Can I add methods to an existing object?

Replies are listed 'Best First'.
Re^2: Can I add methods to an existing object?
by mr_mischief (Monsignor) on Apr 02, 2009 at 21:12 UTC
    You can also declare that as:

    sub Hubba::bubba { print "bubba" }

    which looks more intuitive to me. BTW, is the "Bubba" capitalized in the name of the bubble gum brand?

      This is not quite the same thing.

      Your approach declares the bubba-method at compile-time, my example at run-time.

      You could not use your approach e.g. in a context where the name of the method to be added in not known at compile-time (e.g. is entered by the user).

      And "hubba" and "bubba" are my just my personal preference for generic names that I use where others may use "foo" and "bar" that others prefer - I can't remember where I got that from initially but it has nothing to do with bubble gum :-)

        pileofrogs didn't specify that it needs to be done at run-time. It would be my preference to resolve such issues at compile-time unless there is some feature of the final product that required deferral of the sub declaration until run-time.

        It is good to make the difference clear, I guess, just in case the difference really matters to someone looking for a way to add a class method from outside the package scope. That's not really the question that was asked, since pileofrogs asked about adding a method to an object. In many cases adding a method to the class is just as good as adding it to the object instance, so no harm done from that little difference. It is, BTW, easy to add a non-method subroutine to the object's data structure when using hash-based objects, but that could create more confusion than it solves.

        Just for kicks, I'll give you a link to Hubba Bubba®. It may not be where you got the words, but anyone who grew up chewing this Wrigley® product will recognize the name on sight.