views:

522

answers:

3

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.

+6  A: 

Use grep:

#!/usr/bin/perl

use strict;
use warnings;

my %data = ("A" => 0, "B" => "yes", "C" => 0 );
my @keys = grep { $data{$_} } keys %data;

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:

my @data = ("A" => 0, "B" => 1, "C" => 0 );
my @modified_data = map { $data{$_} + 1 } @data;
print join ' ', @data, "\n";
print join ' ', @modified_data, "\n";
James Thompson
Cool. I have seldom seen the "non-m//" generalized grep in Perl. I usually use "map" for stuff like this, with a block like: { <<cond>> ? $_ : () }. TMTOWTDI, I guess :-)
Roboprog
Roboprog: Indeed. map { ($_)x!!(<<code>>) }, for instance.
ysth
@Roboprog - Thanks. I think this is more concise, but your way is definitely good too.@ysth - can you give a more concrete example? What's up with the !! characters? It's Perl, so I'm tempted to try it. :)
James Thompson
@James Thompson: ()x in list context is the list repetition operator. !!() booleanizes; anything true becomes 1, anything false becomes (in the numeric context provided by ()x) 0. So grep { xxx } is equivalent to map { ($_)x!!( xxx ) } since the $_ will be repeated 0 times when xxx is false and once when xxx is true. I was lightly making fun of the idea of using map to do a grep by showing an even sillier way to do it.
ysth
+10  A: 

I think you want grep:

#!/usr/bin/env perl
use strict;
use warnings;

my %data = ( A => undef, B => 'yes', C => undef );

my @keys = grep { defined $data{$_} } keys %data;

print "Key: $_\n" for @keys;

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 or undef 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 does 0. If 0 is a valid value, then you want to explicitly test for definedness, not simply truth. (I mention it because James went for 0 and I went the other way, and you may or may not know if it matters.)

Telemachus
It doesn't matter that you type slowly, you get more votes anyway! :)
James Thompson
Which is odd, since we wrote essentially the same answer. I completely don't get the voting here.
Telemachus
I think it's a sign that Perl programmers on this site think undef > 0 in this instance. :-P
Chris Jester-Young
Chris has hit the nail on the head here. I've definitely learnt my lesson. :)Voting is odd. No big deal, and you have good answers anyhow so I don't mind.
James Thompson
Yeah the two proposed solutions are very similar, but I think the note about undef was helpful, so I'll go with the majority vote. Thanks, all!
conny
+3  A: 

For variation on the theme have a look at autobox (see its implementations autobox::Core and Moose::Autobox )

use autobox::Core;

my %data = ( A => undef, B => 'yes', C => undef );
my $key_list = %data->keys->grep( sub { defined $data{$_} } );

say "Key: $_" for @$key_list;

# => Key: B


Moose::Autobox comes with key/value 'kv' which makes the code DRYer:

my $key_list = %data->kv->grep( sub{ defined $_->[1] } )->map( sub{ $_->[0] } );

Here is a more explicit and even longer version of above:

my $key_list = %data->kv
                    ->grep( sub { my ($k, $v) = @$_; defined $v } )
                    ->map(  sub { my ($k, $v) = @$_; $k }         );

/I3az/

draegtun