免费注册 查看新帖 |

Chinaunix

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

[help]一个程序。运行结果与预期不符。 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-08-01 16:16 |只看该作者 |倒序浏览
#!/usr/bin/perl -w

my %last_name = qw [fred flintstone Wilma Flintstone Barney Rubble betty rubble Bamm-Bamm Rubble PEBBLES FLINTSONE];

my @keys=sort
{
        "\L$last_name{$a}" cmp "\L$last_name{$b}" or
        "\L$a"           cmp "\L$b"
} keys %last_name;


foreach my $name (@keys)
{
        printf "%-10s%-10s\n",$name,$last_name{$name};
}


哪位能解释一下,为什么结果中PEBBLES出现在最开始?

谢谢。

论坛徽章:
0
2 [报告]
发表于 2006-08-01 17:37 |只看该作者

回复 1楼 CalmIce 的帖子

......
"\L$last_name{$a}" cmp "\L$last_name{$b}"
or
"\L$a"   cmp "\L$b"
.....


Hi,
see the order of compareration's condition:
this order is first compare to hash's value and then hash's key, so the output sorted by hash's value
if you want sort hash's key here, just exchange the order:  
......
"\L$a"   cmp "\L$b"
or
"\L$last_name{$a}" cmp "\L$last_name{$b}"
.....



Best,
    ulmer

--------
Just 4 Fun

[ 本帖最后由 ulmer 于 2006-8-1 17:38 编辑 ]

论坛徽章:
0
3 [报告]
发表于 2006-08-01 20:39 |只看该作者
Thanks for your quick response. ulmer
Nevertheless I do want to compare the hash values first.I mean--
The expected result should be:

fred      flintstone
PEBBLES   FLINTSONE

Wilma     Flintstone
Bamm-Bamm Rubble   
Barney    Rubble   
betty     rubble

But the output of the script comes like below when I run it under FC4 :

PEBBLES   FLINTSONE
fred      flintstone

Wilma     Flintstone
Bamm-Bamm Rubble   
Barney    Rubble   
betty     rubble

That's the part puzzled me.

论坛徽章:
0
4 [报告]
发表于 2006-08-02 08:22 |只看该作者
哈希数组的元素在内存中存储顺序是无序的
任何一个元素都有可能最先被打印出来

论坛徽章:
0
5 [报告]
发表于 2006-08-02 08:51 |只看该作者
不好意思,我看错了

论坛徽章:
0
6 [报告]
发表于 2006-08-02 09:09 |只看该作者
原帖由 ubac 于 2006-8-2 08:22 发表
哈希数组的元素在内存中存储顺序是无序的
任何一个元素都有可能最先被打印出来


This only would happen when you export a hash into an array.But it's not what we are talking about.  :)

论坛徽章:
0
7 [报告]
发表于 2006-08-02 09:20 |只看该作者
  1. my @keys=sort
  2. {
  3.         "\L$last_name{$a}" cmp "\L$last_name{$b}" or
  4.         "\L$a"           cmp "\L$b"
  5. } keys %last_name;
复制代码

以字典顺序进行sort;以value作为主要比较操作,key作为次要比较操作

所以建议
  1. printf "%-10s%-10s\n",$last_name{$name},$name;
复制代码

应该就能发现为什么了




另可以看看仙子的:简简单单讲sort
http://bbs.chinaunix.net/viewthread.php?tid=636546

论坛徽章:
0
8 [报告]
发表于 2006-08-02 13:31 |只看该作者
原帖由 CalmIce 于 2006-8-1 16:16 发表
#!/usr/bin/perl -w

my %last_name = qw [fred flintstone Wilma Flintstone Barney Rubble betty rubble Bamm-Bamm Rubble PEBBLES FLINTSONE];

my @keys=sort
{
        "\L$last_name{$a}"  ...



Sorry to bother. It's just a typo ....
Thank you all.  :)

[ 本帖最后由 CalmIce 于 2006-8-2 13:41 编辑 ]
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP