I am learning about Perl 5's object-oriented programming features and have a question about the "bless" keyword. Bless takes either one or two arguments: the first argument is a reference, and the second (optional) argument is the package to bless the referent into. If the second argument is omitted, it defaults to the current package. My question is: why/how would you ever need to specify a package other than the current package when using bless? Suppose I have the following constructor in Widget.pm:

package Widget; use strict; use warnings; sub new { my $class = shift(); my ($arguments) = @_; my $self = {}; bless $self; }

In this case, the Widget constructor will always be used to construct Widgets, so the second argument to bless can be omitted as it will default to Widget. Under what circumstances would you use one package's constructor to create objects in a different package, thus requiring the second argument to bless?


In reply to questions about bless's second argument by Special_K

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.