htmanning has asked for the wisdom of the Perl Monks concerning the following question:

I have a routine that grabs headlines from my database and then using a 'while' loop, writes the 10 latest headlines to a text file. I then include that file in an html page. What I'm trying to accomplish is to have a variable that auto-increments itself within the while loop so I can print something like:

Headline
variable include 1

Headline
variable include 2

Headline
variable include 3

etc.

I know that is a vague question but since I'm using the While loop, it simply zips through and writes the headlines down. I need to be able to have separate include statements so that I can plug ads in after every 3 headlines or so. Make sense? Thanks. Tom

  • Comment on Auto Incrementing Variable in While Statement

Replies are listed 'Best First'.
Re: Auto Incrementing Variable in While Statement
by ikegami (Patriarch) on Jan 23, 2007 at 05:09 UTC
    my $var; while (...) { ++$var; ... }
    And for "every third",
    my $var; while (...) { ++$var; ... if ($var % 3 == 0) { # Stuff for every third pass. ... } }
Re: Auto Incrementing Variable in While Statement
by logie17 (Friar) on Jan 23, 2007 at 07:01 UTC
    It might help to post the code, however I think you're after something like this:
    my $count = 0; while (..whatever..){ $count++; #do stuff last if $count == 3; }
    Does this help?
    s;;5776?12321=10609$d=9409:12100$xx;;s;(\d*);push @_,$1;eg;map{print chr(sqrt($_))."\n"} @_;
      I may have misunderstood your message. Only use the last statement if you wish to exit the loop.Otherwise ikegami has the correct code/solution.
      apologies for any confusion
      s;;5776?12321=10609$d=9409:12100$xx;;s;(\d*);push @_,$1;eg;map{print chr(sqrt($_))."\n"} @_;
      Okay, I'll try to be clearer here. I've stripped out some code but here is the basics of what I have:
      $SQL = "SELECT * FROM $database_table order by date DESC, ID DESC limi +t 10"; $sth = $dbh->prepare($SQL); $sth->execute; open(TXTFILE, ">$rootpath$categoryDir$frontPage"); while ($pointer = $sth->fetchrow_hashref) { $fullpath = $pointer->{'fullfilepath'}; $name = $pointer->{'filename'}; $thumbnail = $pointer->{'thumbnail'}; $image = $pointer->{'image'}; $imagewidth = $pointer->{'imagewidth'}; $headlinelink = $pointer->{'headlinelink'}; print TXTFILE <<TEXT; <a href=$url NOUNDERLINE id="headline"><font size="+1" face=arial>$tit +le</font></a><br> <font size="1">$category - $month $day, $year $catsiteshow</font><br> TEXT }
      That gives me one text file with 10 headlines formatted how I want it. I'd like to be able insert an ad after the thrid or 4th headline. So I either need a way to print each headline to a separate txt file so that I can include them all in the HTML page manually, or a way to write something into the txt file after the third headline. Make sense? Thanks.