免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
楼主: 小猪Gina
打印 上一主题 下一主题

求助:perl hash中多元键和值的问题 [复制链接]

论坛徽章:
3
CU十二周年纪念徽章
日期:2013-10-24 15:41:34子鼠
日期:2013-12-14 14:57:19射手座
日期:2014-04-25 21:23:23
1 [报告]
发表于 2012-12-10 11:05 |显示全部楼层
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use Data::Dumper;
  5. my %hash;
  6. my $title;
  7. while(<DATA>){
  8.     if(/(\w+\s+(?:\+|-))\s+(\d+)\s+(\d+)/){
  9.         push @{$hash{$1}},$2,$3;
  10.     }else{
  11.         $title = $_;
  12.     }
  13. }
  14. map{print "$_\t";print join("\t",sort{$a cmp $b}@{$hash{$_}});print "\n"}sort keys %hash;

  15. __DATA__
  16. name     direction     start      end
  17. a1           +               4           5
  18. a1           +               1           3
  19. a1           -                2           4
  20. a1           -                5           6
  21. a2           +               3           7
  22. a2           -                1           5
复制代码

论坛徽章:
3
CU十二周年纪念徽章
日期:2013-10-24 15:41:34子鼠
日期:2013-12-14 14:57:19射手座
日期:2014-04-25 21:23:23
2 [报告]
发表于 2012-12-10 11:30 |显示全部楼层
回复 14# 小猪Gina
那更简单一些。。。。
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use Data::Dumper;
  5. my %hash;
  6. my $title;
  7. while(<DATA>){
  8.     if(/(\w+\s+(?:\+|-))\s+(\d+\s+\d+)/){
  9.         push @{$hash{$1}},$2;
  10.     }else{
  11.         $title = $_;
  12.     }
  13. }
  14. map{print "$_\t";print join("\t",sort{$a cmp $b}@{$hash{$_}});print "\n"}sort keys %hash;

  15. __DATA__
  16. a1           +               1           3
  17. a1           +               6           8
  18. a1           -               2           4
  19. a1           -               5           6
  20. a1           -               3           5
  21. a1           -               7           8
  22. a2           +               3           7
  23. a2           -               1           5
  24. a2           +               4           6
  25. a2           -               7           9
  26. a1           +               4           5
  27. a1           +               2           5
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP