1

我是新手。这个我有。。

%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']  
);

我需要它来打印这个..

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

这是到目前为止的代码..

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

正在打印这个..

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

1 回答 1

4

我相信以下应该做你想要的:

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

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

我添加了一个 for 循环来迭代子类别数组的内容。

如果您需要按字母顺序排序的类别和子类别,请尝试以下操作:

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

    my $subcategories = $categories{$cat};

    foreach my $subcat (sort @$subcategories) {
        print "- $subcat\n";
    }
}
于 2012-04-13T01:56:59.723 回答