I'm looking for ways to express this Python snippet in Perl:
data = {"A": None, "B": "yes", "C": None}
key_list = [k for k in data if data[k]]
# in this case the same as filter(lambda k: data[k], data) but let's ignore that
So looking at it one way, I just want the keys where the values are None or undef. Looking at it another way, what I want is the concise perl equivalent of a list comprehension with conditional.
Use grep:
Grep returns the values from the list on the right-hand side for which the expression in braces evaluates to a true value. As telemachus points out, you want to make sure you understand true/false values in Perl. This question has a good overview of truth in Perl.
You'll likely want a look at map, which applies an expression in braces to each element of a list and returns the result. An example would be:
I think you want
grep
:I also think that I type too slowly, and that I should reload the page before posting answers. By the way, either a value of
0
orundef
can be a good way to handle null values, but make sure you remember which you're using. A false value and and undefined value aren't the same thing in Perl. To clarify:undef
returns false in a boolean test, but so does0
. If0
is a valid value, then you want to explicitly test for definedness, not simply truth. (I mention it because James went for0
and I went the other way, and you may or may not know if it matters.)For variation on the theme have a look at autobox (see its implementations autobox::Core and Moose::Autobox )
Moose::Autobox comes with key/value 'kv' which makes the code DRYer:
Here is a more explicit and even longer version of above: