Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Parsing through Hashes

by sidsinha (Acolyte)
on Aug 29, 2014 at 09:22 UTC ( #1098962=perlquestion: print w/replies, xml ) Need Help??
sidsinha has asked for the wisdom of the Perl Monks concerning the following question:

I have an hash of keys and values as below. Each key has multiple values, but each value could reference a key. For a given input key, I need to print the values, and if the value is also a key, then print the value of that key in brackets as below:

Usb1 Usb2,Usb3 Usb2 val1,val2,Usb4 Usb3 val3 Usb4 val4

Input : Usb1 print Usb2[val1,val2,Usb4[val4]],Usb3[val3] Input : Usb2 print val1,val2,Usb4[val4]

The logic I tried is to first check if the input key exists in the hash then load the values of that key into an array Now, iterate through the array, print $_ , then compare if the value matches any key in the hash, if matches, print the value. But now, I dont get how long and how I can keep doing this, because the set of keys could reference another key and so on...

Any suggestions or examples could help. Thankyou

Replies are listed 'Best First'.
Re: Parsing through Hashes
by AppleFritter (Vicar) on Aug 29, 2014 at 09:45 UTC

    Recursion will help you there. (Doing it iteratively instead is also possible, of course, but less natural and elegant.) Here's one solution:

    #!/usr/bin/perl use strict; use warnings; my %hash = ( "Usb1" => "Usb2,Usb3", "Usb2" => "val1,val2,Usb4", "Usb3" => "val3", "Usb4" => "val4" ); say_values(\%hash, "Usb1"); say_values(\%hash, "Usb2"); sub say_values { print_values(@_); print "\n"; } sub print_values { my ($hash_ref, $key) = @_; return unless exists $hash_ref->{$key}; my @values = split ",", $hash_ref->{$key}; foreach my $index (0..$#values) { print $values[$index]; if(exists $hash_ref->{$values[$index]}) { print "["; print_values($hash_ref, $values[$index]); print "]"; } print "," unless $index == $#values; } }

    This produces:

    $ perl Usb2[val1,val2,Usb4[val4]],Usb3[val3] val1,val2,Usb4[val4] $

      Thankyou very much AppleFritter!

      I hadnt gone through recursion so far, but now it seems its a fun thing! I took a while to understand it but its great! thanks a lot again.

        You're very welcome! *tips hat* Enjoy learning Perl, and if you have further questions down the road, the Monastery'll always be here to provide help.
Re: Parsing through Hashes
by sidsinha (Acolyte) on Aug 29, 2014 at 09:27 UTC

    PS: I am trying to learn, so I dont want to use any packages.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1098962]
Approved by marto
Front-paged by toolic
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2018-05-23 00:27 GMT
Find Nodes?
    Voting Booth?