<p>If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys?  I have heard that using <code>each</code> may in some way have unintended side effects.  So, is that true, and is one of the two following methods best, or is there a better way?</p>

<pre><code># Method 1
while (my ($key, $value) = each(%hash)) {
    # Something
}

# Method 2
foreach my $key (keys(%hash)) {
    # Something
}
</code></pre>

[{'answer_id': 3066, 'author': 'jj33', 'author_id': 430, 'author_profile': 'https://Stackoverflow.com/users/430', 'pm_score': 2, 'selected': False, 'text': '<p>I may get bitten by this one but I think that it\'s personal preference.  I can\'t find any reference in the docs to each() being different than keys() or values() (other than the obvious "they return different things" answer.  In fact the docs state the use the same iterator and they all return actual list values instead of copies of them, and that modifying the hash while iterating over it using any call is bad.</p>\n\n<p>All that said, I almost always use keys() because to me it is usually more self documenting to access the key\'s value via the hash itself.  I occasionally use values() when the value is a reference to a large structure and the key to the hash was already stored in the structure, at which point the key is redundant and I don\'t need it.  I think I\'ve used each() 2 times in 10 years of Perl programming and it was probably the wrong choice both times =)</p>\n'}, {'answer_id': 3072, 'author': 'jaredg', 'author_id': 153, 'author_profile': 'https://Stackoverflow.com/users/153', 'pm_score': 2, 'selected': False, 'text': "<p>I always use method 2 as well.  The only benefit of using each is if you're just reading (rather than re-assigning) the value of the hash entry, you're not constantly de-referencing the hash.</p>\n"}, {'answer_id': 3360, 'author': 'John Siracusa', 'author_id': 164, 'author_profile': 'https://Stackoverflow.com/users/164', 'pm_score': 9, 'selected': True, 'text': "<p>The rule of thumb is to use the function most suited to your needs.</p>\n\n<p>If you just want the keys and do not plan to ever <em>read</em> any of the values, use keys():</p>\n\n<pre><code>foreach my $key (keys %hash) { ... }\n</code></pre>\n\n<p>If you just want the values, use values():</p>\n\n<pre><code>foreach my $val (values %hash) { ... }\n</code></pre>\n\n<p>If you need the keys <em>and</em> the values, use each():</p>\n\n<pre><code>keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop\nwhile(my($k, $v) = each %hash) { ... }\n</code></pre>\n\n<p>If you plan to change the keys of the hash in any way <em>except</em> for deleting the current key during the iteration, then you must not use each().  For example, this code to create a new set of uppercase keys with doubled values works fine using keys():</p>\n\n<pre><code>%h = (a =&gt; 1, b =&gt; 2);\n\nforeach my $k (keys %h)\n{\n  $h{uc $k} = $h{$k} * 2;\n}\n</code></pre>\n\n<p>producing the expected resulting hash:</p>\n\n<pre><code>(a =&gt; 1, A =&gt; 2, b =&gt; 2, B =&gt; 4)\n</code></pre>\n\n<p>But using each() to do the same thing:</p>\n\n<pre><code>%h = (a =&gt; 1, b =&gt; 2);\n\nkeys %h;\nwhile(my($k, $v) = each %h)\n{\n  $h{uc $k} = $h{$k} * 2; # BAD IDEA!\n}\n</code></pre>\n\n<p>produces incorrect results in hard-to-predict ways.  For example:</p>\n\n<pre><code>(a =&gt; 1, A =&gt; 2, b =&gt; 2, B =&gt; 8)\n</code></pre>\n\n<p>This, however, is safe:</p>\n\n<pre><code>keys %h;\nwhile(my($k, $v) = each %h)\n{\n  if(...)\n  {\n    delete $h{$k}; # This is safe\n  }\n}\n</code></pre>\n\n<p>All of this is described in the perl documentation:</p>\n\n<pre><code>% perldoc -f keys\n% perldoc -f each\n</code></pre>\n"}, {'answer_id': 22669, 'author': 'Gary Richardson', 'author_id': 2506, 'author_profile': 'https://Stackoverflow.com/users/2506', 'pm_score': 2, 'selected': False, 'text': '<p>I usually use <code>keys</code> and I can\'t think of the last time I used or read a use of <code>each</code>.</p>\n\n<p>Don\'t forget about <code>map</code>, depending on what you\'re doing in the loop!</p>\n\n<pre><code>map { print "$_ =&gt; $hash{$_}\\n" } keys %hash;\n</code></pre>\n'}, {'answer_id': 57767, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Using the each syntax will prevent the entire set of keys from being generated at once.  This can be important if you\'re using a tie-ed hash to a database with millions of rows.  You don\'t want to generate the entire list of keys all at once and exhaust your physical memory.  In this case each serves as an iterator whereas keys actually generates the entire array before the loop starts.</p>\n\n<p>So, the only place "each" is of real use is when the hash is very large (compared to the memory available).  That is only likely to happen when the hash itself doesn\'t live in memory itself unless you\'re programming a handheld data collection device or something with small memory.</p>\n\n<p>If memory is not an issue, usually the map or keys paradigm is the more prevelant and easier to read paradigm.</p>\n'}, {'answer_id': 67239, 'author': 'Michael Carman', 'author_id': 8233, 'author_profile': 'https://Stackoverflow.com/users/8233', 'pm_score': 3, 'selected': False, 'text': '<p>A few miscellaneous thoughts on this topic:</p>\n\n<ol>\n<li>There is nothing unsafe about any of the hash iterators themselves. What is unsafe is modifying the keys of a hash while you\'re iterating over it. (It\'s perfectly safe to modify the values.) The only potential side-effect I can think of is that <code>values</code> returns aliases which means that modifying them will modify the contents of the hash. This is by design but may not be what you want in some circumstances.</li>\n<li>John\'s <a href="https://stackoverflow.com/questions/3033/safest-way-to-iterate-through-the-keys-of-a-perl-hash#3360">accepted answer</a> is good with one exception: the documentation is clear that it is not safe to add keys while iterating over a hash. It may work for some data sets but will fail for others depending on the hash order.</li>\n<li>As already noted, it is safe to delete the last key returned by <code>each</code>. This is <em>not</em> true for <code>keys</code> as <code>each</code> is an iterator while <code>keys</code> returns a list.</li>\n</ol>\n'}, {'answer_id': 67970, 'author': '8jean', 'author_id': 10011, 'author_profile': 'https://Stackoverflow.com/users/10011', 'pm_score': 5, 'selected': False, 'text': '<p>One thing you should be aware of when using <strong><code>each</code></strong> is that it has\nthe side effect of adding "state" to your hash (the hash has to remember\nwhat the "next" key is). When using code like the snippets posted above,\nwhich iterate over the whole hash in one go, this is usually not a\nproblem. However, you will run into hard to track down problems (I speak from\nexperience ;), when using <code>each</code> together with statements like\n<code>last</code> or <code>return</code> to exit from the <code>while ... each</code> loop before you\nhave processed all keys.</p>\n\n<p>In this case, the hash will remember which keys it has already returned, and\nwhen you use <code>each</code> on it the next time (maybe in a totaly unrelated piece of\ncode), it will continue at this position. </p>\n\n<p>Example:</p>\n\n<pre><code>my %hash = ( foo =&gt; 1, bar =&gt; 2, baz =&gt; 3, quux =&gt; 4 );\n\n# find key \'baz\'\nwhile ( my ($k, $v) = each %hash ) {\n    print "found key $k\\n";\n    last if $k eq \'baz\'; # found it!\n}\n\n# later ...\n\nprint "the hash contains:\\n";\n\n# iterate over all keys:\nwhile ( my ($k, $v) = each %hash ) {\n    print "$k =&gt; $v\\n";\n}\n</code></pre>\n\n<p>This prints:</p>\n\n<pre><code>found key bar\nfound key baz\nthe hash contains:\nquux =&gt; 4\nfoo =&gt; 1\n</code></pre>\n\n<p>What happened to keys "bar" and baz"? They\'re still there, but the\nsecond <code>each</code> starts where the first one left off, and stops when it reaches the end of the hash, so we never see them in the second loop.</p>\n'}, {'answer_id': 73004, 'author': 'Darren Meyer', 'author_id': 7826, 'author_profile': 'https://Stackoverflow.com/users/7826', 'pm_score': 4, 'selected': False, 'text': '<p>The place where <code>each</code> can cause you problems is that it\'s a true, non-scoped iterator.  By way of example:</p>\n\n<pre><code>while ( my ($key,$val) = each %a_hash ) {\n    print "$key =&gt; $val\\n";\n    last if $val; #exits loop when $val is true\n}\n\n# but "each" hasn\'t reset!!\nwhile ( my ($key,$val) = each %a_hash ) {\n    # continues where the last loop left off\n    print "$key =&gt; $val\\n";\n}\n</code></pre>\n\n<p>If you need to be sure that <code>each</code> gets all the keys and values, you need to make sure you use <code>keys</code> or <code>values</code> first (as that resets the iterator).  See the <a href="http://perldoc.perl.org/functions/each.html" rel="noreferrer">documentation for each</a>.</p>\n'}, {'answer_id': 4489750, 'author': 'Hogsmill', 'author_id': 545865, 'author_profile': 'https://Stackoverflow.com/users/545865', 'pm_score': -1, 'selected': False, 'text': '<p>I woudl say:</p>\n\n<ol>\n<li>Use whatever\'s easiest to read/understand for most people (so keys, usually, I\'d argue)</li>\n<li>Use whatever you decide consistently throught the whole code base. </li>\n</ol>\n\n<p>This give 2 major advantages:</p>\n\n<ol>\n<li>It\'s easier to spot "common" code so you can re-factor into functions/methiods.</li>\n<li>It\'s easier for future developers to maintain.</li>\n</ol>\n\n<p>I don\'t think it\'s more expensive to use keys over each, so no need for two different constructs for the same thing in your code.</p>\n'}]
['https://Stackoverflow.com/questions/3033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/219/']