Chinaunix

标题: [help]一个程序。运行结果与预期不符。 [打印本页]

作者: CalmIce    时间: 2006-08-01 16:16
标题: [help]一个程序。运行结果与预期不符。
#!/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出现在最开始?

谢谢。
作者: ulmer    时间: 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 编辑 ]
作者: CalmIce    时间: 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.
作者: ubac    时间: 2006-08-02 08:22
哈希数组的元素在内存中存储顺序是无序的
任何一个元素都有可能最先被打印出来
作者: ubac    时间: 2006-08-02 08:51
不好意思,我看错了
作者: CalmIce    时间: 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.  :)
作者: ubac    时间: 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
作者: CalmIce    时间: 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 编辑 ]




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2