我在 Perl 中的问题是这样的:
从标准输入中读取一系列员工编号和每日工作时间,一组 perl 行。员工编号和工作时间应用空格分隔。使用哈希计算总工作小时数和每个工作周期的平均小时数。按排序的员工编号、工作时段数、工作总小时数和每个工作时段的平均小时数打印报告。假设一些员工是兼职的,并且工作的天数或小时数与普通员工不同。
我的脚本是:
#!/usr/bin/perl
use strict;
use warnings;
my @series = qw(41234 9 67845 8 32543 10 84395 7 57543 9 23545 11);
my $workper = 3;
my %empwork;
while (my $series = shift @series) {
my $nums = shift @series;
$empwork{$series} += $nums;
}
my $tot;
foreach (sort keys %empwork) {
$tot += $empwork{$_};
}
my $avg = $tot/$workper;
print "Sorted Employee Numbers:\n";
foreach my $empnum(sort keys %empwork) {
print "$empnum\n";
}
print "The number of work periods is $workper\n";
print "Total number of hours is $tot\n";
print "Average number of hours per work period is $avg\n";
我的输出是:
Sorted Employee Numbers:
23545
32543
41234
57543
67845
84395
The number of work periods is 3
Total number of hours is 54
Average number of hours per work period is 18
谁能告诉我我是否在脚本中做错了什么。如果是,请帮忙。提前致谢。
如果我像这样使用循环 %empwork 一次:
foreach my $empnum(sort keys %empwork) {
$tot += $empwork{$_};
print "$empnum\n";
}
然后我将得到输出:
Sorted Employee Numbers:
23545
32543
41234
57543
67845
84395
The number of work periods is 3
Total number of hours is 0
Average number of hours per work period is 0
Use of uninitialized value in hash element at /tmp/135043087931085.pl line 16.
Use of uninitialized value in addition (+) at /tmp/135043087931085.pl line 16.
Use of uninitialized value in hash element at /tmp/135043087931085.pl line 16.
Use of uninitialized value in addition (+) at /tmp/135043087931085.pl line 16.
Use of uninitialized value in hash element at /tmp/135043087931085.pl line 16.
Use of uninitialized value in addition (+) at /tmp/135043087931085.pl line 16.
Use of uninitialized value in hash element at /tmp/135043087931085.pl line 16.
Use of uninitialized value in addition (+) at /tmp/135043087931085.pl line 16.
Use of uninitialized value in hash element at /tmp/135043087931085.pl line 16.
Use of uninitialized value in addition (+) at /tmp/135043087931085.pl line 16.
Use of uninitialized value in hash element at /tmp/135043087931085.pl line 16.
Use of uninitialized value in addition (+) at /tmp/135043087931085.pl line 16.
我尝试了如下程序。但它不起作用。
#!/usr/bin/perl
use strict;
use warnings;
my @series = qw(41234 9 67845 8 32543 10 84395 7 57543 9 23545 11 23545 1 23545 2 23545 6);
my $total_periods = 0;
my $total_hours = 0;
my %empwork;
while (my $series = shift @series)
{
my $nums = shift @series;
$empwork{$series} += $nums;
}
print "Sorted Employee Numbers:\n";
foreach my $empnum(sort keys %empwork)
{
my $periods=0;
$periods++;
my $hours = 0;
$hours += $empwork{$empnum};
my $avg = $hours/$periods;
$total_periods += $periods;
$total_hours += $hours;
print "$empnum\n$periods periods\n$hours hours\n$avg average\n\n";
}
my $grand_avg = $total_hours/$total_periods;
print "The number of work periods is $total_periods\n";
print "Total number of hours is $total_hours\n";
print "Average number of hours per work period is $grand_avg\n";
我哪里错了?