在Perl中将多个值转换为哈希值

时间:2014-03-17 06:21:32

标签: perl hash

我应该在具有多个值的文本文件中读取,例如:

maclawty796 pts/1 75-30-120-13.lig Wed Oct 12 19:27 - 19:33  
maclawty796 pts/1 75-30-120-13.lig Wed Oct 12 19:35 - 19:38  
hturner pts/1 tom-nilsons-macb Wed Oct 12 13:30 - 13:32  
nnt pts/2 99-59-5-115.ligh Tue Oct 11 15:51 - 15:54

并将它们转换为月份的总计,例如:

Ehowe Sep 145 minutes   
Ehowe Oct 38  minutes   
maclawty796 Sep 240  minutes    
maclawty796 Oct 155  minutes

到目前为止,我的代码是:

$file = 'C:\Users\user\Desktop\perlintro\timelog.txt';
open(TimeLog, $file) or die "Couldn't open timelog.txt";

use strict; my $username; my $months; my $time; my $minutes1; my $minutes2; my $seconds1; my $seconds2; my $oneLine; my %hash = (); while (<TimeLog>) { $oneLine=$_; if ( ($username) = /([[a-y]*(\d|\w)*)/) { printf "%-12s", $username; } if ( ($months) = /((Jan) | (Feb) | (Mar) | (Apr) | (May) | (Jun) | (Jul) | (Aug) | (Sep) | (Oct) | (Nov) | (Dec) )/ ) { printf ("%-7s", $months); } if ( ($minutes1, $seconds1, $minutes2, $seconds2) = /(\d\d):(\d\d)\s-\s(\d\d):(\d\d)/ ) { $time = ($minutes2 * 60 + $seconds2) - ($minutes1 * 60 + $seconds1); printf ("%-3s minutes\n", $time); } for my $username (keys(%hash)) { for my $months (keys(%{ $hash{$username} })) { print("$username $months $hash{$username}{$months}\n"); } } }

所以,目前它每天打印一次,但我需要帮助才能让它按月打印。

1 个答案:

答案 0 :(得分:1)

试试这个:

#!/usr/bin/perl

use warnings;
use strict;

my %time_log;
while (<DATA>) {
    chomp;
    my ($user, undef, undef, undef, $mon, undef, $time1, undef, $time2) = split;
    $time_log{$user}->{$mon} += time_diff($time1, $time2)
}

while (my ($user, $mons) = each %time_log) {
    while (my ($mon, $period) = each %$mons) {
        print "$user $mon $period\n";
    }
}

sub time_diff {
    my ($time1, $time2) = @_;

    my ($hh1, $mm1, $hh2, $mm2) = split /:/, "$time1:$time2";

    return ($hh2 - $hh1) * 60 + ($mm2 - $mm1);
}

__DATA__
maclawty796 pts/1 75-30-120-13.lig Wed Oct 12 19:27 - 19:33  
maclawty796 pts/1 75-30-120-13.lig Wed Oct 12 19:35 - 19:38  
hturner pts/1 tom-nilsons-macb Wed Oct 12 13:30 - 13:32  
nnt pts/2 99-59-5-115.ligh Tue Oct 11 15:51 - 15:54