views:

80

answers:

2

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??

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} :-(

+4  A: 

%items is a hash of hash references (conceptually, a hash of hashes). $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'.

(corrected based on comments)

Lou Franco
@Lou - thank you for your reply. When you say "then you get back another hash" with 2 new keys...then is it referring back to itself?
jda6one9
No, conceptually each hash key-value pair in items is a key to another hash. $set is a key into %items. You get back another hash for each key. It's like a two-level tree. $set is the first level, then a-logdate is the second level.
Lou Franco
+2  A: 
Ryan Mentley
Corrected my answer based on this info -- thanks.
Lou Franco