【问题标题】:how to count duplicate values of array with hashreference如何使用哈希引用计算数组的重复值
【发布时间】:2019-04-05 15:51:05
【问题描述】:

我想计算散列中数组的值并将它们添加到散列中。我的代码如下所示:

while(my $line=<$fh>) {

                    $timestamp = $1 if $line=~ /^\s*<timestamp>(.*)</;
                    $timestamp =~ s/^(\d\d\d\d-\d\d-\d\d)T.*\s*$/$1/;
                    $errorCode= $1 if $line=~ /^\s*<errorCode>(.*)</;

                    $hash{$timestamp}             = {} unless($hash{$timestamp});
                    $hash{$timestamp}{$errorCode} = [] unless($hash{$timestamp}{$errorCode});

                                    push @{$hash{$timestamp}{$errorCode}}, $1 if $line =~ /<errorText>(.*)</;
            }

输出

   '2019-04-05' => {    '5005' => [
                                    'Dies ist kein aktives Konto',
                                    'Dies ist kein aktives Konto'
                                  ],
                        '7112' => [
                                    'Eingabefelder nicht richtig gefuellt.',
                                    'Eingabefelder nicht richtig gefuellt.',
                                    'Eingabefelder nicht richtig gefuellt.'
                                  ],
                   }

我想要的是这样的:

'2019-04-05' => {    '5005' => { 'Dies ist kein aktives Konto' => 2 },
                     '7112' => { 'Eingabefelder nicht richtig gefuellt.' => 3 },
                }

谁能帮我解决这个问题?提前致谢。

【问题讨论】:

  • 嗨 melpomene,是的,正确。我会编辑它
  • 提示:始终使用use strict; use warnings;
  • 提示:使用 XML::LibXML 之类的 XML 解析器!它不再复杂,它会为您省去很多麻烦!
  • 提示:my ($date) = $timestamp =~ /^([^T])/;my ($date) = split(/T/, $timestamp); 是提取日期的更简洁的方法。
  • 提示:你使用的是$errorCode,即使你没有设置它!!!使用my ($error_code) = $line =~ /&lt;errorCode&gt;(.*)&lt;/ ? $1 : "";

标签: perl hash


【解决方案1】:

你可以这样做

while (my $line=<$fh>) {
    $timestamp = $1 if $line=~ /^\s*<timestamp>(.*)</;
    $timestamp =~ s/^(\d\d\d\d-\d\d-\d\d)T.*$/$1/;
    $errorCode= $1 if $line=~ /^\s*<errorCode>(.*)</;

    $hash{$timestamp}{$errorCode}{$1}++ if $line =~ /<errorText>(.*)</;
}

无需检查中间结构是否存在并手动创建它们。 Autovivification 会解决这个问题。

只需添加另一层哈希键访问并增加值。你最终会得到一个值的计数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-16
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    相关资源
    最近更新 更多