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

I having been looking at this for a while and I can't figure out why its happening (I am still a newbie BTW!). Here is a snippet of the code. I am using strict params too.

The problem is that, near the end, in the while($query_handle->fetch()) part. If I print the the $get_file I get a list of each row as planned. However, if I push that string into the array and then print the array I get a really long list of duplicate entries!

....... my $dsn = "dbi:$platform:$database:$host:$port"; my $connect = DBI->connect($dsn, $user, $pw); foreach my $k(@shows_array) { my($show_id,$title,$next_episode) = split(/\|/,$k); my $query = "SELECT count(episode) from shows where episode = \"$next_ +episode\""; my $query_handle = $connect->prepare($query); $query_handle->execute(); $query_handle->bind_columns(\$episode); { if($episode eq "0") { $get_file = "$url$title"." "."$next_episode"."&catid=$cati +d"."&num=".$num."&age="."$age"."&username=".$username."&".$apikey; #print "<br />".$get_file."<br />"; #THE PRINT ABOVE OUTPUTS FINE push(@nzb_list,$get_file); print @nzb_list; #THE PRINT ABOVE IS THE PROBLEM }; } }
Can anyone see my mistake?

Replies are listed 'Best First'.
Re: Strange loop output
by wind (Priest) on Apr 21, 2011 at 08:10 UTC

    Don't print your array within the loop. Instead wait until you're loop is finished before printing it.

    Otherwise, you'll just get each subsequent build on the @array showing the duplicate items

    On a side note, add error checking to your database connect and the execution of your statement handle. Also if you use placeholders, you can prepare your statement handle just once

    my $dsn = "dbi:$platform:$database:$host:$port"; my $connect = DBI->connect($dsn, $user, $pw) or die "DB connect failed: $DBI::errstr"; my $query_handle = $connect->prepare(q{SELECT count(episode) from show +s where episode=?}); foreach my $k (@shows_array) { my ($show_id, $title, $next_episode) = split /\|/, $k; $query_handle->execute($next_episode) or die $connect->errstr; $query_handle->bind_columns(\my $episode); if($episode eq "0") { my $get_file = "$url$title $next_episode&catid=$catid&num=$num +&age=$age&username=$username&$apikey"; push @nzb_list, $get_file; } } print @nzb_list;
      It doesn't seem to matter where I print. I just took it out of the loop and the same problem occurs!
        Actually - it does matter where I print it! Moving it outside the loop makes it work correctly - thanks. I didn't know, and still don't, how that makes a difference!