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

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

2006-02-03 Retitled by g0n, as per Monastery guidelines
Original title: 'LOOP Help!!!'

Replies are listed 'Best First'.
Re: Remember previous element in a loop
by Corion (Patriarch) on Feb 03, 2006 at 11:39 UTC

    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; };
      Ofcourse... It's programming 101... Thanx for you help
Re: Remember previous element in a loop
by tweetiepooh (Hermit) on Feb 03, 2006 at 11:43 UTC
    Just set $prev lower down and initialise outside of loop.
    $prev = <some dummy value>; for (......) { $data = <get data>; $element = <get element>; ... process data allowing for dummy value in $prev ... $prev = $element; }
Re: Remember previous element in a loop
by blazar (Canon) on Feb 03, 2006 at 13:25 UTC

    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!

    Also, all in all perl-style for loops are preferrable over C-style ones, but in this case I think it's customary to do

    while (my $data = $sth->fetchrow_hashref) { # ...

    instead.