That can be done easily with an object that takes charge of the reblessing and which reverts what it did at destruction time. Your illustration code would look like:

package boo; sub to_s { "a boo" }; package bar; sub to_s { "a bar" }; package main; sub doit { my $boo = shift; my $reblesser = Reblesser->new; $reblesser->rebless($boo, "bar"); print "within: ", $boo->to_s, "\n"; # "a bar" # here the scope of the reblesser ends and so the reblessing it did } my $obj = bless {}, 'boo'; print "before: ", $obj->to_s, "\n"; # "a boo" doit($obj); print "after: ", $obj->to_s, "\n"; # "a boo" again
The output should be:
$ perl reblesser.pl before: a boo [DEBUG] reblessing boo=HASH(0x102efcf8) to bar within: a bar [DEBUG] reverting blessing on bar=HASH(0x102efcf8): back to boo after: a boo
This way you just have to be sure that the scope in which you want to limit the reblessing is the same as the scope of the reblesser object. A trivial implementation of such reblesser would be:
package Reblesser; use strict; use warnings; use base qw(Class::Accessor); __PACKAGE__->mk_accessors(qw(reblessed)); use Scalar::Util qw(blessed); # reblessed holds pairs [ (object => original_package) ] sub new { my $self = shift; return $self->SUPER::new({ reblessed => [] }); } sub rebless { my $self = shift; my $obj = shift; my $package = shift; die "not blessed" unless blessed $obj; push @{$self->reblessed}, [ $obj, blessed $obj ]; warn "[DEBUG] reblessing $obj to $package\n"; return bless $obj, $package } sub DESTROY { my $self = shift; for (@{$self->reblessed}) { my ($obj, $pkg) = @$_; warn "[DEBUG] reverting blessing on $obj: back to $pkg\n"; bless $obj, $pkg; } }

In reply to Re: limiting the scope of bless by ferreira
in thread limiting the scope of bless by jaa

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.