Reblessing is one approach for doing foreign inheritance in inside-out objects without using a facade. For example, what if you want to keep additional state with a filehandle object? The following code is adapted from File::Marker:

package File::With::State; use strict; use warnings; use Scalar::Util qw( refaddr ); use base 'IO::File'; my %stash; # hold inside-out state sub new { my $class = shift; # create the object and rebless my $self = IO::File->new(); bless $self, $class; # initialize the object $stash{ refaddr $self } = {}; $self->open( @_ ) if @_; return $self; } sub stash { my ($self, $key, $value) = @_; return unless $key; $stash{ refaddr $self }{ $key } = $value if $value; return $stash{ refaddr $self }{ $key }; } # Note: this simple example is not thread-safe and also # needs a destructor to avoid leaking memory

The advantage of this over the facade pattern is that you can use the object directly wherever you would use a filehandle.

my $fh = File::With::State->new( 'some_file' ); my @lines = <$fh>; $fh->stash( line_count => scalar @lines );

I think this use of reblessing is "safe" because it reblesses into a subclass, which means that all the methods of the original class are available (although they could be overridden as usual with subclassing). No functionality is lost through the reblessing.

-xdg

Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.


In reply to Re: Re-blessing || Re-constructing objects by xdg
in thread Re-blessing || Re-constructing objects by blogical

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.