title: How to check if a Perl hash is defined when it doesn't have any key/value pairs
body: <p>I'm trying to figure out a way to check if a hash has been declared in a Perl script while inside a module function.</p>
  <p>Given the following script (file <em>script.pl</em>):</p>
  <pre><code>#!/usr/bin/perl -w
  
  use strict;
  use checkHash;
  
  our %testHash = (&quot;key&quot;=&gt;&quot;value&quot;);
  
  print &amp;checkHash() ? 1 : 0;
  </code></pre>
  <p>Along with this module (<em>checkHash.pm</em>);</p>
  <pre><code>sub checkHash {
      if(%main::testHash) {
          return 1;
      }
      else {
          return 0;
      }
  }
  
  1;
  </code></pre>
  <p>Running on a Mac with <a href="https://en.wikipedia.org/wiki/Mac_OS_X_Snow_Leopard" rel="nofollow noreferrer">OS X v10.6.7</a> (Snow Leopard) and Perl v5.10.0, the return value of checkHash is &quot;1&quot; which I would expect. However, if I remove the key value pair from the script by changing the line:</p>
  <pre><code>our %testHash = (&quot;key&quot;=&gt;&quot;value&quot;);
  </code></pre>
  <p>to:</p>
  <pre><code>our %testHash = ();
  </code></pre>
  <p>The return value is &quot;0&quot;. My original assumption was that this would be &quot;1&quot;, but after reading about the way the test I'm using is testing for the size in the hash, I see why that was incorrect thinking.</p>
  <p><strong>Is there a test that can be used in the checkHash module that will return true if the hash it's testing exists, but doesn't have any keys assigned to it?</strong></p>