Is there a quick, perlish way to perform either of these 2 operations

What about a way to do both :-)

if(scalar @{[ delete @hash{keys %hash} ]}) { print "Hash was not empty\n"; } else { print "Hash was empty\n"; }

The delete function returns a list of the deleted values. If there were no keys in the hash then the list will be empty. I found that if the hash contained one key with a value of undef then scalar delete @hash{keys %hash} evaluated to false - hence the anonmous array gymnastics.

My code is actually checking whether the hash was empty (and in the same step emptying it), but to go back to your original question, you define empty as "all elements are undef" which is a mighty unusual definition of empty. Surely if it's empty, there are no elements.

You may be confused by the fact that refering to a hash key that does not exist returns undef. If the hash key does exist, but its value is undef, then the hash is not empty - it has at least one key. The 'exists' function is what you'd use to check for the existence of a particular key.

If your hash might have undefined values but you just want to know if there are any defined values, you could say:

if(grep defined($_), values %hash) { ... }

In reply to Re: Checking and undef'in hash elements in one step? by grantm
in thread One liner to Check and undef hash elements by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.