t a
t a

Reputation: 201

Perl array hash print

I'm a novice. I've got this..

%categories = (
    'Announcements' => ['Auctions', 'Bands-Seeking-Members', 'Boutiques', 'Charity'],  
    'Appliances' => ['Dishwashers', 'Fireplaces/Wood-Burning-Stoves', 'Microwaves'],  
    'Auto-Parts-and-Accessories' => ['Auto-Accessories', 'Car-Audio-and-Video],  
    'Baby' => ['Baby-Clothing', 'Backpacks-and-Carriers', 'Changing', 'Cribs-and-Playpens'],  
    'Books-and-Media' => ['Blu-ray-Discs', 'Books:-Children'],  
    'Clothing-and-Apparel' => ['Boys-Clothing', 'Boys-Shoes', 'Costumes']  
);

I need it to print this..

• Announcements  
 -Auctions  
 -Bands-Seeking-Members  
 -Boutiques  
 -Charity  
•Appliances etc  

This is the code so far..

while( my ($cat,$subcat) = each %categories) {      
    print qq~• $cat
~;  
    print qq~- $subcat
~;  
}  

It's printing this..

• Clothing-and-Apparel  
- ARRAY(0x1e959c0)  
• Announcements  
- ARRAY(0x1e95590)  
• Auto-Parts-and-Accessories  
- ARRAY(0x1e95740)  

Upvotes: 1

Views: 1363

Answers (1)

mttrb
mttrb

Reputation: 8345

I believe the following should do what you want:

while(my ($cat, $subcats) = each %categories) {
    print "• $cat\n";

    foreach my $subcat (@$subcats) {
        print "- $subcat\n";
    }
}

I have added a for loop to iterate over the contents of your subcategory arrays.

If you need the categories and subcategories sorted alphabetically, try this:

foreach my $cat (sort keys %categories) {
    print "• $cat\n";

    my $subcategories = $categories{$cat};

    foreach my $subcat (sort @$subcategories) {
        print "- $subcat\n";
    }
}

Upvotes: 4

Related Questions