Paul Johnson wrote:
On Sun, Jun 15, 2003 at 09:35:38PM +0200, Marcin Kasperski wrote:

Does there exist some way to protect before this problem (some kind of
auto-destructor, finally, whatever which would automatically rewind
the hash internal iterator while leaving the context)?

Not really a mod_perl problem, but you can read about the solution in the docs for each.

   There is a single iterator for each hash, shared by all "each",
   "keys", and "values" function calls in the program; it can be reset
   by reading all the elements from the hash, or by evaluating "keys
   HASH" or "values HASH".

I found this note before asking, believe me... But it seems to me that this solution is not satisfactory - calling
'keys' or 'values' is inefficient and destroys most gains from
iterating over the hash using each...


Calling keys() (or values()) in void context is quite efficient.

Whether or not you appreciate the aesthetics is perhaps quite another
matter.

I think the point that Marcin is trying to make is that under normal circumstances (a script is run once) this problem doesn't occur. However under mod_perl the code persists and therefore doesn't DWIM, till you start thinking in mod_perl terms and not one-time run script terms.


The problem can be classified into "the global variables usage under mod_perl" category.

Consider:

#!/usr/bin/perl -T

our %hash;
%hash = map {$_ => 1 } 'a'..'c' unless %hash;

print "Content-type: text/plain\n\n";

for (my ($k, $v) = each %hash) {
    print "$k $v\n";
    last;
}

that script prints different values on the first 3 invocations and prints nothing on the 4th, and then repeats the loop. (when you run with httpd -X). there are 3 hash key/value pairs in that example.

As Paul has suggested you need to reset the iterator as documented for the operator each(). So adding:

keys %has;

does the trick for the above example.

p.s. I've shown an example, so we can have this issue documented together with other mod_perl gotchas. It's interesting that I don't remember this issue being reported earlier.

__________________________________________________________________
Stas Bekman            JAm_pH ------> Just Another mod_perl Hacker
http://stason.org/     mod_perl Guide ---> http://perl.apache.org
mailto:[EMAIL PROTECTED] http://use.perl.org http://apacheweek.com
http://modperlbook.org http://apache.org   http://ticketmaster.com



Reply via email to