Getting multiple values into a hash in Perl

大憨熊 提交于 2019-12-25 18:47:10

问题


I am supposed to read in a text file with multiple values such as:

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

and turn them into totals for the month, such as:

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

So far my code is:

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

So, currently it prints every single day, but I need help to make it only print by month.


回答1:


Try this:

#!/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


来源:https://stackoverflow.com/questions/22448098/getting-multiple-values-into-a-hash-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!