in reply to why "Bless" in OO Perl

bless causes the reference contained in its first parameter to become an object of the class specified in the second argument. The reference is essentially "blessed into a class.", or possibly more descriptively, "promoted", or "reborn" into a class.

Before being blessed, a reference is just a reference. After being blessed, it's an object instance of a particular class.

If you're looking for a good book on the subject, I highly recommend merlyn's "Alpaca book", Learning Perl Objects, References & Modules.


Dave

Replies are listed 'Best First'.
Re^2: why "Bless" in OO Perl
by Fletch (Bishop) on May 03, 2006 at 13:13 UTC

    Actuall the thing being referenced is blessed; the reference is still just a reference. The blessing changes the referent, not the reference itself. A new reference taken to the same referent will exhibit blessed / object-y behavior.</pedant>

    use strict; {package Foo; sub oik { print "oik\n" } } my $x = bless [], "Foo"; $x->oik; our @y; *y = $x; ( \@y )->oik;

    Zaxo's explanation below shows this as well.

      You are absolutely correct. ...it's a concept I understand but have difficulty expressing clearly, especially in a layman vocabulary. Good job with the linguistic deobfuscation. ;)

      I might add, the referent needn't be a hash, a simple scalar, nor an array. It could also be a file handle, a regexp, and even a sub, though I've never figured out a useful purpose to blessing a sub. Now I'm sure someone will follow-up with a brilliant use of this technique. *grin*


      Dave

        OO: extending a closure object was an example of using a closure as an object base type. The blessed sub is the only possible accessor. It allowed the object to be very opaque, but I didn't see it as enough of a benefit to recommend it.

        Caution: Contents may have been coded under pressure.

        Not brlliant but see Re: How to store CODE ref for a method of accessing the source for a coderef without resorting to B:: trickery (of course it's not perfect since it doesn't preserve closureness, but then that's a hard problem no matter what . . .).

        Update: Never mind, that's not blessing the coderef directly it's overloading &{}. I thought I'd done something similar with blessed coderefs. Hrmm . . .