Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The rule of thumb is to use the function most suited to your needs.</p> <p>If you just want the keys and do not plan to ever <em>read</em> any of the values, use keys():</p> <pre><code>foreach my $key (keys %hash) { ... } </code></pre> <p>If you just want the values, use values():</p> <pre><code>foreach my $val (values %hash) { ... } </code></pre> <p>If you need the keys <em>and</em> the values, use each():</p> <pre><code>keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop while(my($k, $v) = each %hash) { ... } </code></pre> <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> <pre><code>%h = (a =&gt; 1, b =&gt; 2); foreach my $k (keys %h) { $h{uc $k} = $h{$k} * 2; } </code></pre> <p>producing the expected resulting hash:</p> <pre><code>(a =&gt; 1, A =&gt; 2, b =&gt; 2, B =&gt; 4) </code></pre> <p>But using each() to do the same thing:</p> <pre><code>%h = (a =&gt; 1, b =&gt; 2); keys %h; while(my($k, $v) = each %h) { $h{uc $k} = $h{$k} * 2; # BAD IDEA! } </code></pre> <p>produces incorrect results in hard-to-predict ways. For example:</p> <pre><code>(a =&gt; 1, A =&gt; 2, b =&gt; 2, B =&gt; 8) </code></pre> <p>This, however, is safe:</p> <pre><code>keys %h; while(my($k, $v) = each %h) { if(...) { delete $h{$k}; # This is safe } } </code></pre> <p>All of this is described in the perl documentation:</p> <pre><code>% perldoc -f keys % perldoc -f each </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload