Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Fundamentally, a hash is a data structure optimized for solving the converse question, knowing whether the <em>key</em> 2 is present. But it's hard to judge without knowing, so let's assume that won't change.</p> <p>Possibilities presented here will depend on:</p> <ul> <li>how often you need to do it</li> <li>how dynamic the hash is</li> </ul> <h2>One-time op</h2> <ul> <li><code>grep $_==2, values %x</code> (also spelled <code>grep {$_==1} values %x</code>) will return a list of as many 2s as are present in the hash, or, in scalar context, the number of matches. Evaluated as a boolean in a condition, it yields just what you want.<br> <a href="http://perldoc.perl.org/functions/grep.html" rel="noreferrer"><code>grep</code></a> works on versions of Perl as old as I can remember.</li> <li><code>use List::Util qw(first); first {$_==2} values %x</code> returns only the first match, <code>undef</code> if none. That makes it faster, as it will short-circuit (stop examining elements) as soon as it succeeds. This isn't a problem for 2, but take care that the returned element doesn't necessarily evaluate to boolean true. Use <code>defined</code> in those cases.<br> <a href="http://perldoc.perl.org/List/Util.html#first-BLOCK-LIST" rel="noreferrer"><code>List::Util</code></a> is a part of the Perl core since 5.8.</li> <li><code>use List::MoreUtils qw(any); any {$_==2} values %x</code> returns exactly the information you requested as a boolean, and exhibits the short-circuiting behavior.<br> <a href="http://search.cpan.org/perldoc/List::MoreUtils" rel="noreferrer"><code>List::MoreUtils</code></a> is available from CPAN.</li> <li><code>2 ~~ [values %x]</code> returns exactly the information you requested as a boolean, and exhibits the short-circuiting behavior.<br> <a href="http://perldoc.perl.org/perlsyn.html#Smart-matching-in-detail" rel="noreferrer">Smart matching</a> is available in Perl since 5.10.</li> </ul> <h2>Repeated op, static hash</h2> <p>Construct a hash that maps values to keys, and use that one as a natural hash to test key existence.</p> <pre><code>my %r = reverse %x; if ( exists $r{2} ) { ... } </code></pre> <h2>Repeated op, dynamic hash</h2> <p>Use a reverse lookup as above. You'll need to keep it up to date, which is left as an exercise to the reader/editor. (hint: value collisions are tricky)</p>
 

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