terrabl
terrabl

Reputation: 944

Trouble with simple arithmetic in perl

At the moment I'm having trouble doing simple arithmetic seen in the code snippet below, I think the problem may be due to scope but I'm fairly new and don't fully comprehend the scope problem that I may be facing, any help would be greatly appreciated. Thanks.

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";

Upvotes: 0

Views: 66

Answers (2)

Borodin
Borodin

Reputation: 126762

You're writing a parser in a language you don't fully know yet. Parsers are hard, so I think you should start with something else

You must always use strict and use warnings 'all' at the top of every Perl program you write. That would have alerted you top finalnumber1 not being declared. And all declarations should be made as late as possible -- usually where they are first defined

It's not clear what you intended to happen after the second number! Don't use overly long identifiers like $firstnumber1 etc., and if you find that you're using identifiers with numbers at the end then it's a sign that you need an array instead

Here's my take on what you were trying to do

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";

output

char = A
char = D
char = D
char = (
char = 5
firstnumber = 5
char = ,
char = 4
secondnumber = 4
char = )
char = ;
9 = 5 + 4

Upvotes: 1

Michael Albers
Michael Albers

Reputation: 3779

Looks like the $digitCount increment should be inside the two if blocks. Right now you'll increment it when you process the A and then on the D, etc. so by the time you get to the 5 $digitCount will be 4 and you're if conditions will never be true.

Upvotes: 0

Related Questions