I've been playing around with Perl over the last couple of days to see what I can do with references. I really get annoyed with having to test everything to see if it is blessed before testing to see if it matches the interface that I'm expecting:
if (blessed( $arg ) && $arg->isa('Some::Class')) {
#
}
So what I've been trying to do is get it so that references are automagically blessed into a class that shares the name of their reference type:
% perl -Mmagicrefs -MData::Dumper -e 'print Dumper( {} )'
$VAR1 = bless( {}, 'HASH' );
And it all works, so now I can do:
use lib './lib';
use strict;
use magicrefs; ## turn on magic references
my $c = {
Auto => 'blessed',
refs => 'are',
fun => '.'
};
print $c->keys->join(','),"\n";
## or ##
if ($c->keys->grep( sub {
print "right\n";
} else {
print "wrong\n";
}
## or ##
my %hash = $c->deref;
## or with the magic of deparse
print sub { 1; }->code(), "\n";
I'm guessing the chances of this going into the core are pretty slim however
UNIVERSAL::isa (Score:4, Interesting)
#!perl -l
$x = {};
print UNIVERSAL::isa($x,"Foo::Bar") ? 1 : 0;
print UNIVERSAL::isa($x,"HASH") ? 1 : 0;
__END__
0
1
(as documented in the UNIVERSAL manpage)
Reply to This
Re:UNIVERSAL::isa (Score:2, Interesting)
Re:UNIVERSAL::isa (Score:3, Interesting)
Re:UNIVERSAL::isa (Score:1)
Re:UNIVERSAL::isa (Score:2)
Re:UNIVERSAL::isa (Score:1)
Essentially it alters S_refto in pp.c. magicrefs.pm sets a hint that is examined in S_refto to determine whether or not we should bless all references that are created (with the exception of those that are SvREADONLY). magicrefs also use's the various reftype modules.
Re:UNIVERSAL::isa (Score:2)
Re:UNIVERSAL::isa (Score:1)
You could probably do this by overloading the dereferencing operators.
Obviously, at the expend of acceptable performance.
Newfangled (Score:3, Informative)
Reply to This
Possible breakage (Score:4, Informative)
blessedwhich you've just broken.Let's fix that
(untested code, of course)Reply to This