-
July 15th, 2007, 08:23 PM
#1
Learning perl, need some help.
I am using a tutorial I found on the internet to learn perl and at the end of each chapter it gives you some practice problems. I just completed the chapter on arrays and lists and the problem is this.
Write a program that reads lines of input containing numbers, each of which is
separated by exactly one space, and prints out the following:
a. The total for each line
b. The grand total
This is what I have so far
Code:
#!/usr/bin/perl
############READ IN THE LINES OF NUMBERS#############
$grandtotal = 0;
$line = <STDIN>;
while ($line ne ""){
chop($line);
@numbers = split(/ /,$line);
$position = 0;
$total = 0;
while($position <= @numbers){
$total = $total + $numbers[$position];
$position++;
}
print($total, "\n");
$grandtotal = $grandtotal + $total;
}
print("The Grand total is $grandtotal.\n");
It doesn't show any errors, but acts very wierd when I run it. I need to be able to enter several lines but it acts like my loop falls through after only one line of input. I'm suspecting my conditional is not doing what I want it to. I'm sure its going to be something very simple that I have done wrong. Thanks for the help.
Band-aid
-
July 19th, 2007, 10:52 PM
#2
Re: Learning perl, need some help.
Instead of using...
Code:
while($position <= @numbers){
$total = $total + $numbers[$position];
$position++;
}
Use foreach...Read about it here.
If the post was helpful...Rate it! Remember to use [code] or [php] tags.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|