High Performance Linux

Tuesday, January 10, 2012

List Comprehensions in Perl

Some time ago I found List comprehension article in Wikipedia. There are many examples for languages which natively support List Comprehension (mainly functional languages), but also few examples of similar constructs for languages which have not embedded list comprehension.I wonder why there is no Perl examples.

Although Perl doesn't have native list comprehension it is very easy to do with map and grep constructions. Let's consider couple of examples.

At first lets see how to implement example of list comprehension construction for Python from the article (I replaced 101 by 5 for shorter output):

$ python -c 'print [2 * x for x in range(5) if x ** 2 > 3]'
[4, 6, 8]

In Perl it would be (Dumper output is reformatted for brevity):

$ perl -MData::Dumper -e 'print Dumper([map { $_ * 2 } \
                                        grep { $_ ** 2 > 3 } (0..4)])'
$VAR1 = [4, 6, 8];

Other example for list of lists generation

$ python -c 'print [(i,j) for j in range(2, 5) for i in range(1,j)]'
[(1, 2), (1, 3), (2, 3), (1, 4), (2, 4), (3, 4)]

and its Perl analog is (Dumper output is reformatted for brevity)

$ perl -MData::Dumper -e 'print Dumper([map { $n = $_; \
                                        map {[$_,$n]} (1..$n - 1)} \
                                        (2..4)])'
$VAR1 = [
          [1, 2],
          [1, 3],
          [2, 3],
          [1, 4],
          [2, 4],
          [3, 4]
        ];

No comments:

Post a Comment