perl - Why is the perl hash overwriting previous data?
问题描述
So, I'm writing data into my hash which is %errordata
. It looks like this
sub openfile
{
if (open my $data, "<", $filename)
{
my $line = <$data>;
print "Error: $line";
my $dir = cwd;
print "$dir\n";
$errordata{$line} = $dir;
while (my($keys,$values) = each %errordata) {
print "$keys in $values\n";
}
}
The first two print output that I got looks something like this
FIRST
ERROR: quick brown fox
/abc/efg/hij/klm
SECOND
ERROR: quick brown fox
/abc/efg/hij/gvb
But every time it encounters the same output it overwrites it but I want to save the path because it may be different.
FIRST
quick brown fox in /abc/efg/hij/klm
SECOND
quick brown fox in /abc/efg/hij/klm
Should I use push (@{%hash{"KEYNAME"} }, "new value")
? If so, can anyone elaborate on this? I'm not sure how to go on about this.
Any suggestions would be helpful. Thank you!
解决方案
Perl hash assumes that each key is unique. If you would like to store more than one value or data structure under one key you need apply some logic how to achieve desired result.
Please see the following demo code to sort teachers and students from incoming data.
use strict;
use warnings;
use feature 'say';
use Data::Dumper;
my %people;
my $re = qr/(\S+)\s+(.*)/;
while( <DATA> ) {
my($title,$name) = /$re/;
push @{$people{$title}}, $name;
}
say Dumper(\%people);
while( my($title,$group) = each %people ) {
say ucfirst $title . ':';
say "\t$_" for @{$group};
}
__DATA__
teacher Alex Trump
student Amanda Torry
student Nick Popler
student Jonny Sleeper
student Natalie Simpson
teacher George Magic
student Tom Smarty
teacher Pat Golder
Output
$VAR1 = {
'teacher' => [
'Alex Trump',
'George Magic',
'Pat Golder'
],
'student' => [
'Amanda Torry',
'Nick Popler',
'Jonny Sleeper',
'Natalie Simpson',
'Tom Smarty'
]
};
Teacher:
Alex Trump
George Magic
Pat Golder
Student:
Amanda Torry
Nick Popler
Jonny Sleeper
Natalie Simpson
Tom Smarty
推荐阅读
- gcc - 如何修复“警告 #1173-D:属性“已弃用”被忽略?
- python - Sagemaker 调用端点返回值类型?
- android - ConditionVariable 在 AsyncTask 中不起作用
- ios - 在 ios 11 中的 whatsapp 上共享带有标题的图像
- html - 输入元素的 HTML 模式验证
- excel - 根据另一个单元格的内容将格式应用于单元格的一部分
- php - 如何将 a 标签包裹在 div 标签周围?
- c# - Try-Catch 中的“catch”是哪种数据结构或构造
- python - 检查 uint16 是否在范围内的最快方法,包括溢出时换行
- reactjs - React - 冒号被替换