Learning perl, need some help.
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Learning perl, need some help.

  1. #1
    Join Date
    Feb 2007
    Posts
    4

    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

  2. #2
    PeejAvery's Avatar
    PeejAvery is offline Super Moderator Power Poster
    Join Date
    May 2002
    Posts
    10,860

    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
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center