Perl equivalent of (Python-) list comprehension


Question

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.

1
13
7/10/2009 11:39:07 PM

Accepted Answer

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.)

21
7/10/2009 11:55:59 PM

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";

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon