Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: quick question about hash element access

by jdklueber (Beadle)
on Jun 28, 2003 at 00:23 UTC ( [id://269779]=note: print w/replies, xml ) Need Help??


in reply to quick question about hash element access

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
  • Comment on Re: quick question about hash element access

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://269779]
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-25 23:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found