假设在文件number_list.txt中给出了一组数字。从以下类别的文件中找到数字的总和:
Sum of all 1 digits numbers
Sum of all 2 digits numbers
Sum of all 3 digits numbers
Sum of all numbers starting with a digit 7
Sum of all number ending with a digit 8
在perl中编写代码以找到上述总和
示例:如果我们有“number_list.txt”
23
258
1
24
57
76
85
72
4
654
958
6
46
358
然后我们需要得到这样的答案
Sum of all 1 digits numbers
1 + 4 + 6 = 11
Sum of all 2 digits numbers
23 + 24 + 57 + 76 + 85 + 72 + 46 = 383
Sum of all 3 digits numbers
258 + 654 + 958 + 358 = 2228
Sum of all numbers starting with a digit 7
76 + 72 = 148
Sum of all number ending with a digit 8
258 + 358 + 958 = 1574
到目前为止,我已经做到了。
#!/usr/bin/perl
use strict;
use warnings;
my $filename = "numbers.txt";
open( my $fh, '<', $filename ) or die "Can't open $filename: $!";
my @array1;
my @array2;
my @array3;
my @array4;
print "\n \n";
while ( my $line = <$fh> ) {
#if ( length($line) == 1)
#{
# push (@array1, $line);
#}
if ( length($line) == 2)
{
push (@array2, $line);
}
if ( length($line) == 3)
{
push (@array3, $line);
}
if ( length($line) == 4)
{
push (@array4, $line);
}
}
#print "\n Sum of all digits numbers\n \n";
#for each (@array1) {
# print "$_";
# }
my $sum1 = 0;
my $sum2 = 0;
my $sum3 = 0;
print "\n \n Sum of all 1 digits numbers of:\n \n";
for each my $num2 (@array2) {
print "$num2";
$sum1 = $sum1 + $num2;
}
print "\n Sum = $sum1";
print "\n \n Sum of all 2 digits numbers of:\n \n";
for each my $num3 (@array3) {
print "$num3";
$sum2 = $sum2 + $num3;
}
print "\n Sum = $sum2";
print "\n \n Sum of all 3 digits numbers of:\n \n";
foreach my $num4(@array4) {
print "$num4";
$sum3 = $sum3 +$num4;
}
print "\n Sum = $sum3";
所以我很难以简单的方式制作这个程序。有什么简单的方法可以做这个程序吗?
而且我也很难得到
Sum of all numbers starting with a digit 7
Sum of all number ending with a digit 8