tags:

views:

501

answers:

3

From perldoc -f bless:

bless REF,CLASSNAME

This function tells the thingy referenced by REF that it is now
an object in the CLASSNAME package.

Is there any way of obtaining an unblessed structure without unnecessary copying?

+8  A: 

Acme::Curse :)

Update: Thank you, Ivan! I mixed up modules. Actually I wanted to give a link to Acme::Damn :))

P. S. See also Acme::Sneeze :)

P. P. S. It has no real use, that's why it's Acme::. See brian's post.

codeholic
But this module creates copy of the object.
Ivan Nevostruev
Attributed to Mike Andrews in alt.sysadmin.recovery: "Perl already has _bless_, and we know what it does, right? Perl should also have _smite_, and we know what it should do, too. If more languages had _smite_ implemented, the remaining programmers would be better than the current average."
Jim Lewis
+7  A: 

Data::Structure::Util

unbless($ref)

Remove the blessing from any objects found within the passed data structure.

#!/usr/bin/perl

use strict; use warnings;

use Scalar::Util qw( refaddr );
use Data::Structure::Util qw( unbless );

my $x = bless { a => 1, b => 2 } => 'My';

printf "%s : %s\n", ref $x, refaddr $x;

unbless $x;

printf "%s : %s\n", ref $x, refaddr $x;

Output:

My : 237356
HASH : 237356
Sinan Ünür
+8  A: 

Why do you need to unbless it? Are you doing this for one of your own classes or a different class? This sounds suspiciously like The Wrong Thing To Do.

You have the same problem as breaking encapsulation because you have to assume that you know what the internal structure of the reference is. If you are going to do that, you can just ignore the object-oriented stuff and access the structure directly.

If you are going to do this for your own class, consider providing a method to return a data structure (which doesn't have to be the original structure) instead of changing the object.

You mention in a follow-up comment that you might be doing this to get around some Template Toolkit behavior. I had this situation in two ways depending on the situation:

  • Only pass the data you need to the template instead of the whole object.
  • Add methods to the object to get the data you want in the template.

Perl is DWIM, but TT is even DWIMmier, which is unfortunate sometimes.

brian d foy
+1 for getting to the real problem.
Ether