Khatri has asked for the wisdom of the Perl Monks concerning the following question:

how can one write method which can dynamically create instance of different/same classes by taking name of instance?
  • Comment on how to create instances of classes ....

Replies are listed 'Best First'.
Re: how to create instances of classes ....
by japhy (Canon) on Sep 28, 2005 at 15:37 UTC
    This sounds like basic inheritance.
    package Parent; sub new { my ($class, @args) = @_; bless [ @args ], $class; } package Child; @ISA = 'Parent';
    Calling Child->new will call Parent's new() method, but $class will be 'Child', not 'Parent'.

    The "trick" is using the first argument to the class method as the class name, not hardcoding the class name into your code.


    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: how to create instances of classes ....
by Happy-the-monk (Canon) on Sep 28, 2005 at 15:37 UTC

    Have a look at perltoot and into OO Tutorials in the Tutorials section of the monastery.

    What you need is a constructor that uses the bless function together with the class name.
    You can obtain an object's class name using the ref-function.

    Cheers, Sören

Re: how to create instances of classes ....
by Zaxo (Archbishop) on Sep 28, 2005 at 15:47 UTC

    The ref function returns the class name of an object, so you can bless a reference into a class with it,

    my $object = Foo->new; my $fake = bless {}, ref $object; my $real = (ref $object)->new;
    There is no assurance that Foo's instance methods will work with $fake. Know what your classes are like before you do this.

    You can bless a reference into any namespace you like - it doesn't even have to exist in the symbol table.

    After Compline,
    Zaxo

Re: how to create instances of classes ....
by dragonchild (Archbishop) on Sep 28, 2005 at 16:09 UTC
    sub factory { my $class_name = shift; my @args = @_; return $class_name->new( @args ); } my $foo = factory( 'Class1', $arg1 ); my $bar = factory( 'Class2', $arg2 );
    Though, frankly, since you can use a variable name as I am doing in the factory() function, you can just avoid it altogether.

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?