免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 6377 | 回复: 5
打印 上一主题 下一主题

关于散列读取文件 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-08-27 11:09 |显示全部楼层 |倒序浏览
做了两个文件

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


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

论坛徽章:
0
2 [报告]
发表于 2008-08-27 13:18 |显示全部楼层

回复 #3 cobrawgl 的帖子

hash哪个部分看learningperl很多遍了
估计还是没有参透

你说的收到了

论坛徽章:
0
3 [报告]
发表于 2008-08-27 17:34 |显示全部楼层
看了半个下午了
my $log= shift@ARGV||"chengji.log";
open my $file,"<",$log or die "Fail to open $log $!";
这两句啥意思啊
||不是短路符吗
怎么可能把 chengji.log放到@ARGV里面呢?

论坛徽章:
0
4 [报告]
发表于 2008-08-27 17:44 |显示全部楼层
哦  那我就理解对了 他是短路字符
那  文件是通过
open my $file,"<",$log or die "Fail to open $log $!";

这句来读取的话?

shift @AGRV能读出啥呢

不好意思哈,基础太差
但热情足够  

论坛徽章:
0
5 [报告]
发表于 2008-08-27 17:48 |显示全部楼层
The array @ARGV contains the command-line arguments intended for the script. $#ARGV is generally the number of arguments minus one, because $ARGV[0] is the first argument, not the program's command name itself. See $0 for the command name.

好像明白了  谢谢大家了

论坛徽章:
0
6 [报告]
发表于 2008-08-28 00:41 |显示全部楼层
又仔细看了一下发现 下面的语法在learningperl中都有提到
看书不细
看来真得看上一百遍啊一百遍
my $log= shift@ARGV||"chengji.log";
open my $file,"<",$log or die "Fail to open $log $!";
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP