adding strings, not concatenating them

S

Stan Horwitz

I am working on a perl program where I extract a variable from a line of
input and I want to keep a running count of that variable. I am using
the substr function to extract the variable. For purposes of example,
let's say the extracted variable is called $extracted_variable and my
total variable is called $total. The $extracted_variable comes from
something along the lines of $extracted_variable = substr($stuff, 0, 8);


$total = $total + $extracted_variable;

Let's say $total is initialized to a value of 10 and
$extracted_variable is "900".

I want the result to be 910. I do not want a result of 90010.

How do I do that? My current attempts all result in errors such as

isn't numeric in addition (+) at

and after spending an hour querying books on perl and googling, I am
getting nowhere.

I am sure this is a simple matter, but what's the trick? Do I have to
convert each element in the string to a number? I thought perl just did
that on the fly.
 
J

Joe Smith

Stan said:
$total = $total + $extracted_variable;

Let's say $total is initialized to a value of 10 and
$extracted_variable is "900".

I want the result to be 910. I do not want a result of 90010.

How do I do that? My current attempts all result in errors such as

isn't numeric in addition (+) at

Oh, really?

You need to post a short but complete perl program that
demonstrates this problem before we can help you. I cannot
reproduce the problem from your description.

use warnings;
$stuff=" 900xyz";
$extracted_variable = substr $stuff,0,8;
$total = 10;
print "Before: total='$total' extracted_variable='$extracted_variable'\n";
$total = $total + $extracted_variable;
print "After: total='$total'\n";

-Joe
 
S

Stan Horwitz

Joe Smith said:
Oh, really?

You need to post a short but complete perl program that
demonstrates this problem before we can help you. I cannot
reproduce the problem from your description.

use warnings;
$stuff=" 900xyz";
$extracted_variable = substr $stuff,0,8;
$total = 10;
print "Before: total='$total' extracted_variable='$extracted_variable'\n";
$total = $total + $extracted_variable;
print "After: total='$total'\n";

Joe;

Thanks. As it turns out, the problem wasn't in how I was adding the
string, but how I was parsing it. I was off by a few characters in my
parsing. As a result, my program was trying to add up non-numeric data.
You lead me to the solution because as I was trying to assemble the code
to follow up with your request, I realized my error.

Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top