我有这个代码
use strict; use warnings; my %hash; $hash{'1'}= {'Make' => 'Toyota','Color' => 'Red',}; $hash{'2'}= {'Make' => 'Ford','Color' => 'Blue',}; $hash{'3'}= {'Make' => 'Honda','Color' => 'Yellow',}; foreach my $key (keys %hash){ my $a = $hash{$key}{'Make'}; my $b = $hash{$key}{'Color'}; print "$a $b\n"; }
这个出来了:
Toyota Red Honda Yellow Ford Blue
需要帮助按Make排序.
解决方法
#!/usr/bin/perl use strict; use warnings; my %hash = ( 1 => { Make => 'Toyota',Color => 'Red',},2 => { Make => 'Ford',Color => 'Blue',3 => { Make => 'Honda',Color => 'Yellow',); # if you still need the keys... foreach my $key ( # sort { $hash{$a}->{Make} cmp $hash{$b}->{Make} } # keys %hash ) { my $value = $hash{$key}; printf( "%s %s\n",$value->{Make},$value->{Color} ); } # if you don't... foreach my $value ( # sort { $a->{Make} cmp $b->{Make} } # values %hash ) { printf( "%s %s\n",$value->{Color} ); }