我有一个关于完美匹配的问题。我想从文件中得到正整数和负整数之和。我也想让日期在文件中有相同的值。
我的档案:
Hello -12, 3.4 and 32. Where did you
go on 01/01/2013 ? On 01/01/2013, we
went home. -4 plus 5 makes 1.
03/02/2013
解决方案:
-16 //the sum of negative integers.
38 //the sum of positive integers.
2 //count of dates have same values.
我的代码:
$sum=0;
$sum1=0;
while ($_=<>) {
for each($_=~ /_\d+g){
$sum+=$_;
}
for each($_=~ /_\d+(\.| )/g){
$sum1+=$_;
}
foreach($_=~ / \d{2}(/\d{2}({/\d{4})?)?/ {
$count++;
}
}
print "$sum\n";
print "$sum1\n";
print "$count\n";
}
我的代码错了。请帮忙。我无法在结果上方打印。
答案 0 :(得分:0)
你的代码非常破碎。它包含许多语法错误,您应该在每个脚本中包含use strict;
和use warnings;
。
那就是说,我可以通过演示如何解析文件并同时提取各种正则表达式来帮助你:
use strict;
use warnings;
while (<DATA>) {
print "Processing: $_";
while (m{(\d{2}/\d{2}/\d{4})|(-\d+)|(\d+\.?\d*)}g) {
my ($date, $neg, $pos) = ($1, $2, $3);
if (defined $date) {
print " Found Date: $date\n";
} elsif (defined $neg) {
print " Found Neg: $neg\n";
} elsif (defined $pos) {
print " Found Pos: $pos\n";
}
}
}
__DATA__
Hello -12, 3.4 and 32. Where did you
go on 01/01/2013 ? On 01/01/2013, we
went home. -4 plus 5 makes 1.
03/02/2013
输出:
Processing: Hello -12, 3.4 and 32. Where did you
Found Neg: -12
Found Pos: 3.4
Found Pos: 32.
Processing: go on 01/01/2013 ? On 01/01/2013, we
Found Date: 01/01/2013
Found Date: 01/01/2013
Processing: went home. -4 plus 5 makes 1.
Found Neg: -4
Found Pos: 5
Found Pos: 1.
Processing: 03/02/2013
Found Date: 03/02/2013