CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
lowering one level in hash without knowing the key..

 



zohman
Novice

Dec 15, 2016, 3:52 AM

Post #1 of 5 (6005 views)
lowering one level in hash without knowing the key.. Can't Post

Hi,

is it possible to go down one level in hash without knowing the key?
(and without loop iteration of course)

for example:
i have value in $hash->{'PARENT_KEY'}->{'KEY1'}
also have more values from
$hash->{'PARENT_KEY'}->{'KEY2'}
$hash->{'PARENT_KEY'}->{'KEY3'}
...

i get the $hash output from some query,
at the first lvl of the hash there is the PARENT_KEY and i don't know what
it is, but at this lvl there will be only one key every-time, and i also doesn't care what it will be..

is there anyway to call the first key element or something?
$hash->{0}->{'KEY1'}
$hash->{0}->{'KEY2'}

currently i do iterate with map, like this:

my $key1;
map { $key1 = $hash->{$_}->{'KEY1'}) } keys $hash;


any ideas?

Thanks,
Zohman.


FishMonger
Veteran / Moderator

Dec 15, 2016, 9:47 AM

Post #2 of 5 (5999 views)
Re: [zohman] lowering one level in hash without knowing the key.. [In reply to] Can't Post

If there will only ever be a single key at the first level, then instead of using map, just do a simple assignment.


Code
my ($parent_key) = keys %{ $hash }; 
my $child_value = $hash->{$parent_key}{KEY1};


If you're using a recent version of perl, you don't need to manually dereference $hash like I did to get the parent key.


(This post was edited by FishMonger on Dec 15, 2016, 9:48 AM)


zohman
Novice

Dec 15, 2016, 12:10 PM

Post #3 of 5 (5992 views)
Re: [FishMonger] lowering one level in hash without knowing the key.. [In reply to] Can't Post

i thought it can be done in one line hash call as scalar, but This is also a great technique,
Thanks!


Chris Charley
User

Dec 15, 2016, 5:39 PM

Post #4 of 5 (5980 views)
Re: [zohman] lowering one level in hash without knowing the key.. [In reply to] Can't Post

You could also get the inner keys by calling values on the outer hash. Since there is only one key in the outer hash, values will return only 1 hash reference.


Code
my $hash = { parent_key => { key1 => 'a', key2 => 'b', key3 => 'c'}}; 

my ($inner) = values %$hash;

while (my ($key, $val) = each %$inner) {
say "$key $val";
}



zohman
Novice

Dec 16, 2016, 2:34 AM

Post #5 of 5 (5970 views)
Re: [Chris Charley] lowering one level in hash without knowing the key.. [In reply to] Can't Post

Nice,
i see that i can access values like this now:

$inner->{'key1'}
$inner->{'key2'}
...

so i think it will be more suitable for me,
thanks. :)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives