LOOP Help!!!
Anonymous Monk
created: 2006-02-03 06:34:30
Hi... I need some urgent help please!

How can I remember the previous element in a loop... Here's a sample of a for loop looping through a result set of a DBI query..

for($x=0; $x<$sth->rows; $x++) {
    $data = $sth->fetch_hashref;

    $this = $data->{id};
    $prev = ...
}

Thanks
Re: LOOP Help!!!
created: 2006-02-03 06:39:11

Simply remember your "previous" element before you fetch the next element.

my $data;
for($x=0; $x<$sth->rows; $x++) { 
  my $prev = $data;
  $data = $sth->fetch_hashref; 
  my $this = $data->{id}; 
}

Maybe you should use a different loop style than the C loop for iterating over your results to avoid the polling of $sth->rows:

my $prev;
while (defined my $data = $sth->fetchrow_hashref) {
  my $this = $data->{id};

  ...

  $prev = $data;
};
Re^2: LOOP Help!!!
created: 2006-02-03 06:46:06
Ofcourse... It's programming 101... Thanx for you help
Re: LOOP Help!!!
created: 2006-02-03 06:43:18
Just set $prev lower down and initialise outside of loop.
$prev = ;
for (......) {
    $data = ;
    $element = ;
...
    process data allowing for dummy value in $prev
...
    $prev = $element;
}
Re: LOOP Help!!!
created: 2006-02-03 08:25:50
Maybe I don't understand: the only thing your code seems to miss is the thing you want to assign to $prev which should be presumably $x or something obtained in connection with it. OTOH you iterate over that $x but appear not to use it at all. And as a side note chances are that your code is not strict safe, although you may have my $x; in a part of your program you do not show... but even in that case I would recommend scoping as closely as possible instead!

perlmonks.org content © perlmonks.org and Anonymous Monk, blazar, Corion, tweetiepooh

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03