我已使用Names及其类排名初始化哈希,如下所示
a=>5,b=>2,c=>1,d=>3,e=>5
到目前为止我已经有了这段代码
my %Ranks = reverse %Class; #As I need to find out who's ranked first
print "\nFirst place goes to.... ", $Ranks{1};
代码只打印出来
"First place goes to...."
我希望它打印出来
First place goes to....c
你能告诉我'我在哪里错了吗?
类哈希正确打印 但如果我尝试使用
打印反向哈希foreach $t (keys %Ranks) {
print "\n $t $Ranks{$t}"; }
打印
5
abc23
cab2
ord
如果这有任何帮助
完整代码
#Script to read from the data file and initialize it into a hash
my %Code;
my %Ranks;
#Check whether the file exists
open(fh, "Task1.txt") or die "The File Does Not Exist!\n", $!;
while (my $line = <fh>) {
chomp $line;
my @fields = split /,/, $line;
$Code{$fields[0]} = $fields[1];
$Class{$fields[0]} = $fields[2];
}
close(fh);
#Prints the dataset
print "Code \t Name\n";
foreach $code ( keys %Code) {
print "$code \t $Code{$code}\n";
}
#Find out who comes first
my %Ranks = reverse %Class;
foreach $t (keys %Ranks)
{
print "\n $t $Ranks{$t}";
}
print "\nFirst place goes to.... ", $Ranks{1}, "\n";
答案 0 :(得分:0)
如果要检查数据结构实际包含的内容,请使用Data :: Dumper。 use Data::Dumper; local $Data::Dumper::Useqq = 1; print(Dumper(\%Class));
。你会找到非chomp
ed换行符。
答案 1 :(得分:0)
您需要使用chomp
。目前,您的$fields[2]
值有一个尾随换行符。
将文件读取循环更改为此
while (my $line = <fh>) {
chomp $line;
my @fields = split /,/, $line;
$Code{$fields[0]} = $fields[1];
$Class{$fields[0]} = $fields[2];
}