Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Class / package weak association

by cavac (Parson)
on Jun 08, 2021 at 10:57 UTC ( [id://11133652]=note: print w/replies, xml ) Need Help??


in reply to Class / package weak association

If you think that Perl has not a most generic approach to objects, you'd probably haven't looked into the "huh, this is possible?" corner enough. Take a look at this:

#!/usr/bin/env perl use strict; use warnings; use Data::Dumper; # Turn a scalar into a blessed object my $foo = 'THIS IS A SCALAR'; my $bar = [qw(THIS IS AN ARRAY)]; my $baz = {'This' => 'Is', 'A' => 'Hash'}; 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 itself ;-) no strict 'refs'; *{'This::Is::A::Dummy::Object::stringify'} = sub{ my ($self) = @_; + print Dumper($self); }; } $scalarobject->stringify(); $arrayobject->stringify(); $hashobject->stringify();

This blesses a scalar, an array and a hash with a class that we didn't even create beforehand. AFTER it does that, it modifies the class and adds a "stringify" method, which in turn modifies all the objects of that class. Then we stringify all objects with this newly created method. 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( { 'A' => 'Hash', 'This' => 'Is' }, 'This::Is::A::Dummy::Object' );

If that is not generic and flexible, i don't know what is.

SCNR

perl -e 'use Crypt::Digest::SHA256 qw[sha256_hex]; print substr(sha256_hex("the Answer To Life, The Universe And Everything"), 6, 2), "\n";'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11133652]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-24 00:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found