Last active
December 15, 2016 18:30
-
-
Save mudler/f56d5b748a523625f09ba8ae48ce999b to your computer and use it in GitHub Desktop.
Autoload and hash search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
my $a = MyClass->new; | |
use Data::Dumper; | |
print "Test, searching for 'data': " . $a->test->big->data() . "\n"; | |
print "Test, searching for 'inner': " . $a->big->data() . "\n"; | |
print "Test, searching for 'innest': " . $a->innest() . "\n"; | |
print Dumper( $a->innest ); | |
package MyClass; | |
use Storable qw(dclone); | |
sub new { | |
my $class = shift; | |
my $self = { | |
data => { | |
test => { | |
big => { | |
data => "false" | |
} | |
} | |
, | |
test2 => { inner => "true" } | |
, | |
test3 => { innest => "true" } | |
} | |
}; | |
bless $self, $class; | |
return $self; | |
} | |
sub _search { | |
my ( $hash, $string ) = @_; | |
foreach my $k ( keys %{$hash} ) { | |
return $hash->{$k} if $k eq $string; | |
if ( my $res = _search( $hash->{$k}, $string ) ) { | |
return $res; | |
} | |
} | |
} | |
sub AUTOLOAD { | |
my $config = $AUTOLOAD; | |
$config =~ s/.*:://; | |
return $_[0]->{data}->{$config} | |
if ( exists $_[0]->{data}->{$config} | |
and ref( $_[0]->{data}->{$config} ) ne "HASH" ); | |
my $res = _search( $_[0]->{data}, $config ); | |
if ( defined $res and ( ref($res) eq "HASH" or ref($res) eq "REF" ) ) { | |
my $c = MyClass->new; | |
$c->{data} = dclone($res); | |
return $c; | |
} | |
else { return $res; } | |
return $_[0]; | |
} | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment