【发布时间】:2021-01-16 01:58:27
【问题描述】:
在此代码中,两个键“39”名称相同但值不同,我想打印两个键
use strict;
use warnings;
my %studentnames = (
14 => Martha,
27 =>Vivek,
31 =>Era,
16 =>Marty,
25 =>Jason,
29 =>Socrates,
19 =>Uri,
39 =>Nitin ,
39 =>Plato,
);
foreach my $name (sort keys %studentnames)
{
printf "%-8s %s\n", $name, $studentnames{$name};
}
我遇到了错误。
Bareword "Martha" not allowed while "strict subs" in use at /home/9945b48d30946ed2641d9778b42cb182.pl line 10.
Bareword "Vivek" not allowed while "strict subs" in use at /home/9945b48d30946ed2641d9778b42cb182.pl line 10.
Bareword "Era" not allowed while "strict subs" in use at /home/9945b48d30946ed2641d9778b42cb182.pl line 10.
Bareword "Marty" not allowed while "strict subs" in use at /home/9945b48d30946ed2641d9778b42cb182.pl line 10.
Bareword "Jason" not allowed while "strict subs" in use at /home/9945b48d30946ed2641d9778b42cb182.pl line 10.
Bareword "Socrates" not allowed while "strict subs" in use at /home/9945b48d30946ed2641d9778b42cb182.pl line 10.
Bareword "Uri" not allowed while "strict subs" in use at /home/9945b48d30946ed2641d9778b42cb182.pl line 10.
Bareword "Nitin" not allowed while "strict subs" in use at /home/9945b48d30946ed2641d9778b42cb182.pl line 10.
Bareword "Plato" not allowed while "strict subs" in use at /home/9945b48d30946ed2641d9778b42cb182.pl line 10.
预期输出
14 Martha
27 Vivek
31 Era
16 Marty
25 Jason
29 Socrates
19 Uri
39 Nitin
39 Plato
谁能告诉我怎么做?
【问题讨论】:
-
使用这样的散列的建议很糟糕。你不应该鼓励更多的人在这个前提下解决这个问题。例如,在哈希中,数字
3、3.0和03都将被视为不同,即使它们在数字上相同。您在这里创建的是一个 XY 问题。 -
排序后的预期输出不完全清楚。您的目标是按学生编号排序,然后按学生姓名排序吗?在这种情况下,您为什么期望
16 Marty被排序在31 Era之后?另外,名字是唯一的吗?还是数字 和 名称的组合是唯一的?如果没有任何东西本身或组合是唯一的,则哈希不是正确的数据结构,正如其他人所提到的,您需要一个数组。