Magnolia25 has asked for the wisdom of the Perl Monks concerning the following question:
I am facing problems with below code. This works with my search criteria 'Technology Phones' and returns correct key "TEC-PH 10001949" which is my requirements.
#! perl use strict; use warnings; use Data::Dumper; my %categories = ("FUR-BO 10001798" => 'Furniture', "FUR-CH 10000454" => [ 'Furniture' , 'Chairs'], "OFF-LA 10000240" => [ 'Office Supplies' , 'Labels'] +, "OFF-ST 10000107" => [ 'Office Supplies' , 'Storage' +], "OFF-AR 10003056" => [ 'Office Supplies' , 'Art'], "TEC-PH 10001949" => 'Technology Phones', ); #print Dumper(%categories); print "What is Category code for Technology Phones | Output s +hould be : TEC-PH 10001949? \n"; my $categorycode; my $search = 'Technology Phones'; my @category = (); foreach $categorycode (keys(%categories)) { if(ref($categories{$categorycode}) eq 'ARRAY' and grep { $_ eq $search } @{ $categories{$categorycode} }) { push(@category, $categorycode); } elsif(!ref($categories{$categorycode}) and $categories{$category +code} eq $search) { push(@category, $categorycode); } } print join(", ", @category) . "\n";
However if I change the search = 'Furniture' I need the output as "FUR-BO 10001798" But I get key value "FUR-BO 10001798" & "FUR-CH 10000454" which is not correct.
Also If I give search criteria as 'Office Supplies' , 'Labels' I want my output as "OFF-LA 10000240".
## Facing problems for below serach and desired output print "What is Category code for Furniture | Output s +hould be : FUR-BO 10001798? \n"; print "What is Category code for (Furniture Chairs) | Output s +hould be : OFF-LA 10000240? \n"; print "What is Category code for (Office Supplies Storage) | Output s +hould be : OFF-ST 10000107? \n"; print "What is Category code for (Office Supplies Art) | Output s +hould be : OFF-AR 10003056? \n"; print "What is Category code for (Office Supplies Labels) | Output s +hould be : OFF-LA 10000240? \n";
So $search variable are value/values in my hash and I need to return key as output.
Please help on fixing this. Thanks.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: return Hash key while hash value/values is search criteria
by poj (Abbot) on Jul 01, 2018 at 15:51 UTC | |
by Magnolia25 (Sexton) on Jul 03, 2018 at 03:11 UTC | |
|
Re: return Hash key while hash value/values is search criteria
by NetWallah (Canon) on Jul 01, 2018 at 21:11 UTC | |
by Magnolia25 (Sexton) on Jul 03, 2018 at 03:20 UTC | |
by NetWallah (Canon) on Jul 03, 2018 at 19:07 UTC |