简体   繁体   English

帮助了解Perl哈希

[英]help understanding perl hash

Perl newbie here...I had help with this working perl script with some HASH code and I just need help understanding that code and if it could be written in a way that I would understand the use of HASHES more easily or visually?? 这里的Perl新手...我在使用一些HASH代码的Perl脚本中获得了帮助,我只需要帮助理解该代码,以及是否可以以更容易或更直观地理解HASHES的使用方式来编写它?

In summary the script does a regex to filter on date and the rest of the regex will pull data related to that date. 总之,脚本会执行一个正则表达式以按日期进行过滤,而其余的正则表达式将提取与该日期相关的数据。

use strict;
use warnings;
use constant debug => 0;
my $mon = 'Jul';
my $day = 28;
my $year = 2010;
my %items = ();

while (my $line = <>)
{
    chomp $line;
    print "Line: $line\n" if debug; 
    if ($line =~ m/(.* $mon $day) \d{2}:\d{2}:\d{2} $year: ([a-zA-Z0-9._]*):.*/)
    {
        print "### Scan\n" if debug;
        my $date = $1;
        my $set = $2;
        print "$date ($set): " if debug;
        $items{$set}->{'a-logdate'} = $date;
        $items{$set}->{'a-dataset'} = $set;
        if ($line =~ m/(ERROR|backup-date|backup-size|backup-time|backup-status)[:=](.+)/)
        {
            my $key = $1;
            my $val = $2;
            $items{$set}->{$key} = $val;
            print "$key=$val\n" if debug;
        }
    }
}

print "### Verify\n";
for my $set (sort keys %items)
{
    print "Set: $set\n";
    my %info = %{$items{$set}};
    for my $key (sort keys %info)
    {
        printf "%s=%s;", $key, $info{$key};
    }
    print "\n";
}

What I am trying to understand is these lines: 我想了解的是以下几行:

        $items{$set}->{'a-logdate'} = $date;
        $items{$set}->{'a-dataset'} = $set;

And again couple lines down: 再往下排几行:

        $items{$set}->{$key} = $val;

Is this an example of hash reference? 这是哈希引用的示例吗? hash of hashes? 哈希哈希?
I guess i'm confused with the use of {$set} :-( 我想我对{$ set}的使用感到困惑:-(

%items is a hash of hash references (conceptually, a hash of hashes). %items是哈希引用的哈希(概念上是哈希的哈希)。 $set is the key into %items and then you get back another hash, which is being added to with keys 'a-logdate' and 'a-dataset' . $set%items的键,然后您获得另一个哈希,该哈希将通过键'a-logdate''a-dataset'添加到其中。

(corrected based on comments) (根据评论更正)

Lou Franco's answer is close, with one minor typographical error—the hash of hash references is %items , not $items . Lou Franco的答案很接近,只有一个小的印刷错误-哈希引用的哈希值是%items ,而不是$items It is referred to as $items{key} when you are retrieving a value from %items because the value you are retrieving is a scalar (in this case, a hash reference), but $items would be a different variable. 当您从%items检索值时,它称为$items{key}因为您要检索的值是标量(在这种情况下为哈希引用),但是$items是一个不同的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM