首页 > 解决方案 > 如果两个键相同但值不同,谁能解释如何打印所有键?

问题描述

在此代码中,两个键“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

谁能告诉我该怎么做?

标签: stringperlhash

解决方案


两个键不能相同。一个会覆盖另一个。如果你想为一个键设置多个值,那么你需要设计你的数据结构来支持它(例如,通过让值是一个数组引用)。

您的错误消息与该问题无关(您忘记在字符串值周围加上引号)。


推荐阅读