CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Help with arrays and loops

 



zebu
New User

Feb 4, 2012, 10:36 PM

Post #1 of 5 (944 views)
Help with arrays and loops Can't Post

Hello all,

I am trying to do the following:
use an array and a loop to read stdin until zero is entered. After that I would like to list an output of all the numbers in the loop and calculate the sum.

Where I'm getting stuck: Whenever I specify the array to equal <stdin> within the loop I can't get it to stop when 0 is entered.

Thank you in advance!!!


rovf
Veteran

Feb 6, 2012, 3:57 AM

Post #2 of 5 (916 views)
Re: [zebu] Help with arrays and loops [In reply to] Can't Post

The error is, of course, in line 42 of your program.

(As you certainly know, the people helping at PerlGuru are able to do mind-reading and that's why you don't have to post your code in order to get help).

BTW, it is not possible in Perl to "specify an array to equal <stdin>".....


BillKSmith
Veteran

Feb 6, 2012, 6:18 AM

Post #3 of 5 (906 views)
Re: [zebu] Help with arrays and loops [In reply to] Can't Post

A common error is failing to remove the newline from the number before testing it.

(refer perldoc -f chomp)
Good Luck,
Bill


zebu
New User

Feb 6, 2012, 7:20 PM

Post #4 of 5 (899 views)
Re: [BillKSmith] Help with arrays and loops [In reply to] Can't Post

Bill,

Thanks again. I rewrote my script although I'm having the same issue. I also included the output. I need the last line to list all integers entered into the array (in this case 67, 8) - not just the last integer.

#!/usr/bin/perl
$int = 1;
@list = $int;
foreach $int(@list)
{
while ($int != 0)
{
print ("Enter an integer: ");
$int = <stdin>;
chomp $int;
}
print ("Integers: ", @list[$int]);
}

OUTPUT:

C:\Documents and Settings\Admin\My Documents\Downloads\PERL\comp.pl
Enter an integer: 67
Enter an integer: 8
Enter an integer: 0
Integers: 0

Thank you again, Sir.

BG


BillKSmith
Veteran

Feb 6, 2012, 8:24 PM

Post #5 of 5 (895 views)
Re: [zebu] Help with arrays and loops [In reply to] Can't Post

Always use strict and warnings. They require you to declare all your varaiables (almost always with 'my'). Fix the problems they report.

You are never storing the data in the array. Use push (refer perldoc -f push).


Quote
@list = $int;



This line store a one in the first element of the list. Not what you want!

You should not have nested loops. Your for loop only runs once because the array only contains one value. Get rid of that loop.

Get rid of all subscripts.

Print after the loop completes.

Show us your next version.
Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives