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

Hi!
Why would you bless a ref to CLASS_A inside CLASS_B?

Replies are listed 'Best First'.
•Re: bless!!
by merlyn (Sage) on Jan 17, 2004 at 22:35 UTC
    If a constructor is inherited, it needs to bless into a class that is not its own. As in:
    package CLASS_B; sub new { my $class = shift; # critical here bless { @_ }, $class; # blesses to maybe CLASS_A } package CLASS_A; @ISA = qw(CLASS_B); ... my $object = CLASS_A->new;
    This calls, CLASS_A::new, which inherits to CLASS_B::new, which blesses the hashref into CLASS_A, not CLASS_B. Does that help?

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

      Thank you for pointing out inheritance merlyn!
      I saw something like this a few weeks ago... wish I remembered where exactly.
      package Class_A; sub new { ## the usual: my $class = shift; my $self = {}; bless $self, $class; } sub newB { my $self = {}; bless $self, 'Class_B'; }
      Does this ring any bells?
Re: bless!!
by hardburn (Abbot) on Jan 18, 2004 at 01:11 UTC

    You mean like a factory method? This is done because we may not know the exact subclass we want to use until runtime. For instance, I've got a project I'm working on now where we want to generate different reports in various formats based on the info out of a database. It works by taking the type of report the user wants and looking up (via a hash) which subclass is for that report type. A factory method then blesses a reference into that class and passes the database info in. From there, the subclass can generate whatever kind of data it wants based on what it gets from the database.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    : () { :|:& };:

    Note: All code is untested, unless otherwise stated