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

I find myself using this pattern a lot, and I'm not sure of two things: 1) Is this standard operating procedure and there is a name for it? 2) Is it forward compatible, going to work in perl6? All I'm doing is blessing a reference in the subroutine, "new" and then tying that blessed thingy to the same package. Example, "MyPackage.pm"
package MyPackage; use strict; our $VERSION = 0; use Tie::Hash; use base qw(Tie::ExtraHash); # OO Interface sub new { my $class = ref($_[0]) || $_[0]; my $self = bless {}, $class; tie %$self, $class; } sub to_string { join ' ', %{$_[0]}; } # Tie interface sub STORE { $_[0][0]{$_[1]} = ucfirst($_[2]); } 1;
Example, "t-mypackage.pl" which uses "MyPackage.pm"
#!/usr/bin/perl -w use strict; use MyPackage; my $p = MyPackage->new(); $$p{Hello} = "world"; print $p->to_string, "\n";

Replies are listed 'Best First'.
Re: Blessing into the same package in class (object) and tie contexts
by Arunbear (Prior) on Mar 27, 2008 at 21:28 UTC
    This is not standard operating procedure, as far as I know.
    my $p = MyPackage->new(); $$p{Hello} = "world"; print $p->to_string, "\n";
    Requiring users of MyPackage objects to know that the objects are hashrefs isn't good OO (no encapsulation). And dereferencing the hashref to use it as a tied hash seems convoluted and unnatural e.g. compared to an interface like
    tie my %h, MyPackage; $h{Hello} = "world"; # use tied to call object methods print tied(%h)->to_string, "\n"; # -> 'Hello World'
    i.e. in the example you've given there doesn't seem to be a case for going beyond the standard tied hash semantics.

      I suspected this was not common and appreciate the validation. I have run in to a few stack dumps with different variations on this theme and am concerned that there might be a critical no-no which I'm unaware of.

Re: Blessing into the same package in class (object) and tie contexts
by ikegami (Patriarch) on Mar 27, 2008 at 18:17 UTC
    Why use (ref($_[0]) || $_[0]) in one place and __PACKAGE__ in the other?
    sub new { my $class = (ref($_[0]) || $_[0]); my $self = bless {}, $class; tie %$self, $class; $self }
      Oops, thank you, I updated the post.