1. Shlomi Fish
  2. perl-begin


shl...@13c2ddb8-3aa7-4284-800b-8db07c650eef  committed 2140648

Add modification-during-iter

  • Participants
  • Parent commits ac4b7da
  • Branches default

Comments (0)

Files changed (3)


View file
     - leading underscores ("_") for non-API methods and functions.
     - print {$fh} @args instead of "print $fh @args" which is too easy to miss.
     - STDIN instead of ARGV.
+    - modifying an array/hash while iterating over it.


View file
     - Always label your loops.
     - Accessing the last element using $array[$#array] - use $array[-1]
-    - modifying an array/hash while iterating over it.
     - comments and identifiers in a foreign language. 
 * Link to Fomberg's Hebrew with Perl site.

File src/tutorials/bad-elements/index.html.wml

View file
+<item id="modifying_iterated_array" h="Modifying arrays or hashes while iterating through them.">
+Some people ask about how to add or remove elements to an existing array or
+hash when iterating over them using <tt>foreach</tt> and other loops. The
+answer to that is that Perl will likely not handle it too well, and it expects
+that during loops the keys of a data structure will remain constant. 
+The best way to achieve something similar is to populate a new array or hash
+during the loop by using <pdoc_f f="push">push()</pdoc_f> or a hash lookup
+and assignment. So do that instead.
 #include "bad-elements-sources.wml"