1. Shlomi Fish
  2. perl-begin

Commits

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

Add modification-during-iter

  • Participants
  • Parent commits ac4b7da
  • Branches default

Comments (0)

Files changed (3)

File DONE

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.
 

File TODO

View file
     - Always label your loops.
     - Accessing the last element using $array[$#array] - use $array[-1]
     instead.
-    - 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>
 
+<item id="modifying_iterated_array" h="Modifying arrays or hashes while iterating through them.">
+
+<p>
+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. 
+</p>
+
+<p>
+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.
+</p>
+</item>
+
+
 </main_list>
 
 #include "bad-elements-sources.wml"