Perl: the Markov chain saw | |
PerlMonks |
Re: quick question about hash element accessby jdklueber (Beadle) |
on Jun 28, 2003 at 00:23 UTC ( [id://269779]=note: print w/replies, xml ) | Need Help?? |
This does what I think you're looking for. One caveat: It returns ANYTHING it finds at the end of the argument- even a hash ref (as though you hadn't gotten to the actual terminus). So if that's not what you're intending, you'll need to check your output.
use strict; my %variable_hash; $variable_hash{a}{b}{c}{d} = 40; $variable_hash{e}{f}{g}{h}{i} = 50; $variable_hash{a}{b}{c}{j} = 45; sub get_value { my $argument = shift; my @tmp = split /\./, $argument; my %lastref = %variable_hash; my $max = @tmp; my $current = 0; my $found = 0; foreach my $arg (@tmp) { $current++; last unless (exists($lastref{$arg})); if ($current == $max) { return $lastref{$arg}; } %lastref = %{$lastref{$arg}}; } undef %lastref; return %lastref; } print get_value("a.b.c.d"); print get_value("e.f.g.h.i"); print get_value("a.b.c.j"); print get_value("a.b.c.k"); print get_value("a");-- Jason Klueber ookami@insightbb.com /(bb)|^b{2}/ --Shakespeare
In Section
Seekers of Perl Wisdom
|
|