[Chicago-talk] finding *any* defined elements of a hash

David Mertens dcmertens.perl at gmail.com
Wed Aug 5 11:29:05 PDT 2015


On Wed, Aug 5, 2015 at 2:01 PM, Richard Reina <gatorreina at gmail.com> wrote:

> ...
>
> Can I check to see if any of the hash's element is defined without
> checking all the elements as the hash could grow in the future as the
> fields of the form grow.
> <http://mail.pm.org/mailman/listinfo/chicago-talk>


That sounds like a premature optimization to me. Even the low-level
internals of Perl hashes don't know which of their contents are defined.
But, since it looks like you construct the hash, I would bet that you could
check the return value of param() before adding it to the hash. Something
like this comes to mind (untested):

my %input_hash = map { my $val = param($_); $val ? ($_ => $val) : () }
qw(firstname lastname email);

You can then get the number of elements by getting the number of keys, or
values, in scalar context:

my $N_field_filled_out = scalar(keys %input_hash);

David



-- 
 "Debugging is twice as hard as writing the code in the first place.
  Therefore, if you write the code as cleverly as possible, you are,
  by definition, not smart enough to debug it." -- Brian Kernighan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/chicago-talk/attachments/20150805/2608fa2a/attachment.html>


More information about the Chicago-talk mailing list