目前我在下面的代码段中看到了简单的算术问题,我认为这个问题可能是由于范围问题,但我还是比较新的,并且不完全理解范围我可能面临的问题,任何帮助将不胜感激。感谢。
use POSIX;
use integer;
my $firstnumber1 = 0;
my $secondnumber1 = 0;
my $digitcount = 0;
my $string = "ADD(5,4);";
if($string =~ /^ADD/)
{
foreach my $char (split //, $string)
{
print "char = $char\n";
if((isdigit($char)) && ($digitcount == 0))
{
$firstnumber1 = int($char);
print "firstnumber = $firstnumber1\n";
}
if((isdigit($char)) && ($digitcount == 1))
{
$secondnumber1 = int($char);
print "secondnumber = $secondnumber1\n";
}
$digitcount++;
my $finalnumber1 = $firstnumber1 + $secondnumber1
}
}
print "$finalnumber1 = $firstnumber1 + $secondnumber1";
答案 0 :(得分:1)
您正在用一种您还不完全了解的语言编写解析器。解析器 hard ,所以我认为你应该从别的东西开始
您必须始终 use strict
和use warnings 'all'
位于您编写的每个Perl程序的顶部。这会提醒你最高finalnumber1
没有被宣布。并且所有声明都应尽可能 late - 通常在首次定义时
在第二个数字之后,你不清楚你想要发生什么!不要使用过长的标识符,例如$firstnumber1
等,如果您发现最后使用带有数字的标识符,则表明您需要数组而不是
这是我对你要做的事情的看法
use strict;
use warnings 'all';
use v5.10;
my ($n1, $n2);
my $nc = 0;
my $total = 0;
my $string = 'ADD(5,4);';
if ( $string =~ /^ADD/ ) {
for my $char ( split //, $string ) {
say "char = $char";
if ( $char =~ /[0-9]/ ) {
if ( $nc == 0 ) {
$n1 = $char;
say "firstnumber = $n1";
}
else {
$n2 = $char;
say "secondnumber = $n2";
}
$total += $char;
++$nc;
}
}
}
say "$total = $n1 + $n2";
char = A
char = D
char = D
char = (
char = 5
firstnumber = 5
char = ,
char = 4
secondnumber = 4
char = )
char = ;
9 = 5 + 4
答案 1 :(得分:0)
看起来$digitCount
增量应该在两个if块内。现在,当您处理A
然后处理D
等时,您会增加它,所以当您到达5
$digitCount
时将是4并且你是否条件永远不会成真。