1

Perl 新手在这里...我在这个工作 perl 脚本中得到了一些 HASH 代码的帮助,我只需要帮助理解该代码,如果它可以以一种我更容易或更直观地理解 HASHES 的使用的方式编写?

总之,该脚本执行一个正则表达式来过滤日期,其余的正则表达式将提取与该日期相关的数据。

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";
}

我想了解的是以下几行:

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

又是几行:

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

这是哈希引用的示例吗?哈希的哈希?
我想我对 {$set} 的使用感到困惑 :-(

4

2 回答 2

5

%items是散列引用的散列(概念上是散列的散列)。 $set是进入的关键%items,然后你得到另一个散列,它被添加到键'a-logdate''a-dataset'.

(根据评论更正)

于 2010-08-03T18:17:00.213 回答
2

Lou Franco's answer is close, with one minor typographical error—the hash of hash references is %items, not $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.

于 2010-08-03T18:25:20.673 回答