根据您给@ikegami «我的程序将接受...» 的描述,我创建了一个包含数据的文件:
data_1.txt:
john 10 45 20
alex 30 15 12
pete 23 45 10 21
will 06 56
bob 8 12 3
lazy
请注意,只有前两行实际上与描述相符,我稍后再讨论。
sum.pl:
use strict;
use warnings;
use List::Util 'sum';
# get the two filenames it should work with
#
my $filename_1 = shift;
my $filename_2 = shift;
# be sure we read a file for most modern systems, UTF-8
#
open( my $file1, '<:encoding(UTF-8)', $filename_1)
or die "Can't open file: $filename_1";
# create the (empty) data structure
#
my %sums_and_names;
#
# the % in perl means you are talking about a hash,
# use a sensible name instead of 'hash'
# read line by line
while ( my $line = <$file1> ) {
chomp $line; # get rid of the line endings
my ($name, @grades) = split ' ', $line;
#
# this is not strictly doing what you asked for, just more flexible
#
# split on ' ', a space character, splits on any asmount of (white) space
# your task said that there is one space.
# strictly, you could should split on / /, the regular expression
#
# the first part will go into the variable $name, the rest in array @grades
# strictly you have only three grades so the following would do
# my ($name, $grade_1, $grade_2, $grade_3) = split / /, $line;
my $sum = sum(@grades) // 'no grades';
#
# since we now can handle any number of grades, not just three, we could
# have no grades at all and thus result in `undef`
#
# using the function sum0 would return the value 0 instead
#
# you'll get away with the `undef` using in a hash assignment,
# it will turn it into an empty string `''`
=pod
$sums_and_names{foo}{bar} = [ 'baz', 'qux' ];
=cut
#
# here is where your task doesn't make sense
# i am guessing:
#
$sums_and_names{$sum}{$name} = \@grades;
#
# at least we have all the data from filename_1, and the sum of the grades
}
# please decide on what you want to print
use Data::Dumper;
print Dumper \%sums_and_names;
运行 perl sum.pl data_1.txt data_2.txt 会给你类似的东西
输出:
$VAR1 = {
'no grades' => {
'lazy' => []
},
'23' => {
'bob' => [
'8',
'12',
'3'
]
},
'57' => {
'alex' => [
'30',
'15',
'12'
]
},
'62' => {
'will' => [
'06',
'56'
]
},
'75' => {
'john' => [
'10',
'45',
'20'
]
},
'99' => {
'pete' => [
'23',
'45',
'10',
'21'
]
}
};
请注意,严格来说,while循环内的块可以写成:
chomp $line;
my ($name, $grade_1, $grade_2, $grade_3) = split / /, $line;
$sum = $grade_1 + $grade_2 + $grade_3;
$sums_and_names{$sum}{$name} = [ $grade_1, $grade_2, $grade_3 ];
但我引用@Borodin:
虽然我确定你想要比这更笼统的东西,但你确实没有提供足够的信息