http://qs321.pair.com?node_id=11123862


in reply to questions about bless's second argument

See perlobj for the full story. The short version is that the second argument is the 'class' of the instance being created. If you aren't using inheritance then it's not very interesting. However consider:

use strict; use warnings; package PrintMe; sub AsStr { my ($self) = @_; return $self->{str}; }; sub new { my ($class, $str) = @_; return bless {str => $str}, $class; } package PrintMeToo; use base 'PrintMe'; sub AsStr { my ($self) = @_; return 'Me too: ' . $self->SUPER::AsStr(); }; package main; my $meToo = PrintMeToo->new('This string'); print $meToo->AsStr();

Prints:

Me too: This string

PrintMeToo is derived from PrintMe and inherits the constructor 'new' from PrintMe. Calling the constructor (my $meToo = PrintMeToo->new('This string');) gets the inherited PrintMe constructor called but creates a PrintMeToo instance.

Calling AsStr on the PrintMeToo instance gets the PrintMeToo version of AsStr, but that version calls up to the base class (PrintMe) to get the result from the base class AsStr to concatenate to the text provided by PrintMeToo's AsStr.

Bottom line is, always use the two parameter version of bless and always use the first parameter to the constructor sub to provide the class name.

Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond