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: Intermediate:
Using Counter

 



Lynn
Novice

Sep 20, 2012, 7:58 PM

Post #1 of 4 (2220 views)
Using Counter Can't Post

I feel I am using the counter correctly or pretty close and I don't know why it's just not working correctly. It needs to count the total number of times a condition equals 1 however many times i designate it to run. Instead of count = 30 (30 being the possible number of times the condition is true) it counts each loop like: count 1, count 2, etc....Here is the gist of it.

Code
 
for ($l = 0; $l<=$RUNS; $l++)
{
my $counter = 0;
code....

for (conditions)
{
if(conditions == 1)
{
print stuff
$counter++;
}
print other stuff
}
}

for($counter = 1; $counter <=$RUNS ; $counter++)
{
print "counter $counter\n";
}


jassics
Novice


Sep 21, 2012, 4:13 AM

Post #2 of 4 (2199 views)
Re: [Lynn] Using Counter [In reply to] Can't Post

Lynn,
You are making my $counter = 0; local to your for loop
better put it outside of for loop and it will work it supposed to be.

Every time when when inner for loop get completed it goes to upper for loop check the condition and making $counter = 0; which it should not do so put it outside both foor loop.

like

Code
 my $counter = 0; 
for ($l = 0; $l<=$RUNS; $l++)
{

code....

for (conditions)
{
if(conditions == 1)
{
print stuff
$counter++;
}
print other stuff
}
}

for($counter = 1; $counter <=$RUNS ; $counter++)
{
print "counter $counter\n";
}

Hack to learn! Don't Learn to Hack!


Lynn
Novice

Sep 21, 2012, 6:48 AM

Post #3 of 4 (2191 views)
Re: [jassics] Using Counter [In reply to] Can't Post

It works now. Thank you!


Laurent_R
Veteran / Moderator

Sep 21, 2012, 9:31 AM

Post #4 of 4 (2179 views)
Re: [Lynn] Using Counter [In reply to] Can't Post

Lynn, there might still be a small error in the code after the correction suggested earlier.


Code
 for ($l = 0; $l<=$RUNS; $l++)


looks like a possible error because if $RUNS equals 10, you will run 11 tiBesides mes through the for loop, which is likely to be different from what you want.

Besides, on a purely stylistic point of view, you might consider a more "perlish" syntax.

The code above is better rewritten as:


Code
 for $l (0..$RUNS) {


or, better (but no longer exactly equivalent):

Code
 for my $l (0..$RUNS) {


as it is simpler and more idiomatic and it runs faster (it is equivalent to the above, so it has the same bug if your code had the possible I mentioned.

In fact, since you do not seem to use $l in your loop, it could be even further simplified by dropping $l altogether:


Code
 for (0..$RUNS) {



(This post was edited by Laurent_R on Sep 21, 2012, 9:35 AM)

 
 


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

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