Special_K has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: questions about bless's second argument
by GrandFather (Saint) on Nov 19, 2020 at 23:52 UTC | |
|
Re: questions about bless's second argument
by tybalt89 (Monsignor) on Nov 20, 2020 at 00:13 UTC | |
|
Re: questions about bless's second argument
by Fletch (Bishop) on Nov 19, 2020 at 23:54 UTC | |
|
Re: questions about bless's second argument
by tobyink (Canon) on Nov 20, 2020 at 12:02 UTC | |
| |
|
Re: questions about bless's second argument
by perlfan (Parson) on Nov 20, 2020 at 20:01 UTC |