diotalevi has asked for the wisdom of the Perl Monks concerning the following question:
I have *most* of this code working - it's a demonstration of creating an object with private methods. Under most circumstances those methods *are* private. That falls apart when you use tricks to get to the values. If you read this code you'll see a basic object being created and then the next bit of code reaches in an grabs the lexical hash back out. The part I'm stuck on is how to turn the B::CV entries back into proper code references. I assume B has them somewhere - how do I get B to give them to me? That last step is all that I need to finish the code.
And yes, I do know about PadWalker. I'm trying to do this with stuff that's already in core perl.
use strict; use warnings; use constant DEBUG => 0; use B; { # Get my new really private object where even # the methods are hidden my $object = new object; # and now violate it. Privacy? Ha! my $c_hash = extractLexHash( $object ); while (my ($key, $val) = each %$c_hash ) { print "$key\t$val\n"; } } sub extractLexHash { my $Obj = B::svref_2object($_[0]); my ($LexicalNames, $LexicalValues) = map { [ $_->ARRAY ] } $Obj->PADLIST->ARRAY; # for a cheap thrill print the contents of # $LexicalNames if (DEBUG) { print "Names\n"; print "$_\n" for @$LexicalNames; print "Values\n"; print "$_\n" for @$LexicalValues; exit; } my %Lexicals = (); for my $index (0 .. # min(@LexicalNames, @LexicalValues) (@$LexicalNames < @$LexicalValues ? @$LexicalNames : @$LexicalV +alues)) { next unless B::class($LexicalNames->[$index]) eq 'PVNV'; my @values = $LexicalValues->[$index]->ARRAY; while (@values) { my $LexicalName = shift @values; my $LexicalObj = shift @values; $Lexicals{$LexicalName} = $LexicalObj->RV; } } return \%Lexicals; } package object; sub new { my %methods; %methods = ( me => sub { print "me!\n" }, you => sub { print "you!\n" } ); bless sub { $methods{me}->() }, 'object'; }
|
|---|