in reply to Re^7: Aren't there code refs as well as function refs? (Update: refactoring many variables into hash or object)
in thread Aren't there code refs as well as function refs?
because (most) objects are just blessed hashes
True. Although, as you pointed out, technically not always. As for the classes these objects are blessed with... You can bless a thing with a non-existant class, rewrite the class later on the fly and you are still good.
use strict; use warnings; use Data::Dumper; # Turn stuff into blessed objects my $foo = 'THIS IS A SCALAR'; my $bar = [qw(THIS IS AN ARRAY)]; my $baz = {'This' => 'Is', 'A' => 'Hash'}; # Bless them with a class that doesn't technically exist yet (and have + Perl autovivify it for us) my $scalarobject = bless \$foo, 'This::Is::A::Dummy::Object'; my $arrayobject = bless $bar, 'This::Is::A::Dummy::Object'; my $hashobject = bless $baz, 'This::Is::A::Dummy::Object'; { # Force the This::Is::A::Dummy::Object class to have a print metho +d that stringifies its own object ;-) no strict 'refs'; *{'This::Is::A::Dummy::Object::stringify'} = sub{ my ($self) = @_; + print Dumper($self); }; } $scalarobject->stringify(); $arrayobject->stringify(); $hashobject->stringify();
Result:
$VAR1 = bless( do{\(my $o = 'THIS IS A SCALAR')}, 'This::Is::A::Dummy: +:Object' ); $VAR1 = bless( [ 'THIS', 'IS', 'AN', 'ARRAY' ], 'This::Is::A::Dummy::Object' ); $VAR1 = bless( { 'This' => 'Is', 'A' => 'Hash' }, 'This::Is::A::Dummy::Object' );
I love that you can do stuff like this. Not usually for production code. Although, come to think of it, it might come in handy for that "rewrite my XML config parser" thing i have had on my todo list for a decade now...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^9: Aren't there code refs as well as function refs? (Update: refactoring many variables into hash or object)
by LanX (Saint) on Mar 06, 2023 at 14:04 UTC | |
by cavac (Prior) on Mar 06, 2023 at 14:56 UTC | |
by LanX (Saint) on Mar 06, 2023 at 15:08 UTC |