Exercise 2:
- #! /usr/bin/perl -w
- use strict;
- my %total_bytes;
- my %bytes_sources;
- while(<>)
- {
- next if /^#/;
- my ($source,$dest,$bytes) = split;
- $total_bytes{$source}{$dest} += $bytes;
- }
- #### print the hash according to the bytes of sources
- foreach my $source(keys %total_bytes)
- {
- foreach my $dest (keys %{$total_bytes{$source}})
- {
- $bytes_sources{$source} += $total_bytes{$source}{$dest};
- }
- }
- my %inverse_hash = reverse %bytes_sources;
- foreach my $bytes(reverse sort {$a <=> $b} keys %inverse_hash)
- {
- my $source = $inverse_hash{$bytes};
- printf "Source:%-30ssource_total_bytes:%s\n",${source},$bytes;
- my %inverse_dest = reverse (%{$total_bytes{$source}});
- foreach my $destnum(reverse sort {$a <=> $b}keys %inverse_dest)
- {
- printf "\t\tDest:%-20s\tdest_bytes_from_this_source:%s\n",$inverse_dest{$destnum},$destnum;
- }
- }
- print "\n";
总结:
1.根据原hash的key=>value对建立反向hash的方法:my %inverse_hash = reverse %hash;
2.默认的排序程序根据ascii码顺序来排序列表元素,可以使用subroutine来进行指定高级排序的顺序.如按值排序的方法:
- sort { $a <=> $b} @array; ######code block can be placed directly within brackets
- #####sort using subroutine
- sub my_sort_routine
- {
- ...
- }
- sort my_sort_routine @array;
- ######sort from most to least
- reverse sort {$a <=> $b} @array;
阅读(1516) | 评论(1) | 转发(0) |