关于散列读取文件

关于散列读取文件

做了两个文件

cat chengji.log
id chengji
1 88
2 90
3 85
4 70
5 90
6 99
7 85
8 65
9 70
10 66

现在想用散列按照成绩排序,取出前五名的id
出现的问题是hash对文件读取的时候返回keys 和values 不是我想要的结果
代码如下
##########################
#!/usr/bin/perl
open(OPEN,"chengji.log");
%hash_old=<OPEN>;
chomp(%hash_old);
foreach $key (keys %hash_old){
        #$keys=keys %hash_old;
        $value=$hash_old {$key};
        print "the value is $value \n";
        print "the id is $key \n";
}
#######################
返回结果
the value is 5 90
the id is 4 70

the value is 1 88 90
the id is id chengji

the value is  
the id is 10 66

the value is 9 70
the id is 8 65

the value is 7 85
the id is 6 99

the value is 3 85
the id is 2 90

第二段代码如下
###########################
#!/usr/bin/perl
open(OPEN,"chengji.log");
@OPEN=<OPEN>;
chomp @OPEN;
foreach $chengji (@OPEN){
$chengji="$chengji ";
push(@array,$chengji);
        print "$chengji \n";
}
%HASH=@array;
chomp %HASH;
foreach $key (keys %HASH){
        $value=$HASH{$key};
        print "the value is $value\n";
        print "the id is $key\n";
}
#######################
结果为:
id chengji  
1 88
2 90  
3 85  
4 70  
5 90  
6 99  
7 85  
8 65  
9 70  
10 66  
the value is 5 90
the id is 4 70
the value is 1 88
the id is id chengji
the value is 3 85
the id is 2 90
the value is 7 85
the id is 6 99
the value is
the id is 10 66
the value is 9 70
the id is 8 65


代码写的挺垃圾,请大家谁帮着看一下
想了很长时间了


[Copy to clipboard] [ - ]
CODE:
%hash_old=<OPEN>;

这种牛逼的写法谁教你的?
%hash_old=<OPEN>;  这么写倒是有创意
chomp(%hash_old);     这么写倒是挺NB

lz 好好看看 learning perl 去吧


[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl
use strict;
use warnings;
my $log = shift @ARGV || "chengji.log";
open my $file,"<",$log or die "Fail to open $log $!";
my %score;
while (<$file>){
        next if /^(id chengji)/;
        my ($id,$score) = split /\s+/;
        $score{$id} = $score;
}
print "$_ score $score{$_}\n" foreach ( ( sort { $score{$b} <=> $score{$a} } keys %score)[0..4])

split /\s+/;
通常都写成
split
#!/usr/bin/env perl
use strict;
use warnings;

open CHENGJI, 'chengji.log';
local $/;
$_ = <CHENGJI>;
s/[A-Za-z]+//g;
my %chengji = reverse split;

my @k = reverse sort {$a<=>$b} keys %chengji;
foreach (0..4) {
   print "$chengji{$k[$_]} $k[$_]\n";
}

打印结果
6 99
2 90
1 88
3 85
4 70


QUOTE:
原帖由 khandielas 于 2008-8-27 12:50 发表
#!/usr/bin/env perl
use strict;
use warnings;

open CHENGJI, 'chengji.log';
local $/;
$_ = ;
s/[A-Za-z]+//g;
my %chengji = reverse split;

my @k = reverse sort {$a$b} keys %chengji;
fo ...

很明显不对,90分的有2个。
hash哪个部分看learningperl很多遍了
估计还是没有参透

你说的收到了
呵呵,lz倒是创意很多。呵呵,perl书看起来要细心
受教了
又可以少码些字了
ps:水木perl版版主也是你?