Perl: List Comprehension

By Xah Lee. Date: . Last updated: .

Perl does not have the “list comprehension” as it is. However, in general, functional programing's brevity is more easily achieved in Perl than Python.

Here's a example of generating a list of i*2 for i from 1 to 5:

# -*- coding: utf-8 -*-
# perl

use Data::Dumper;

@myList = map {$_ * 2} (1..5);

print Dumper(\@myList); # [ 2, 4, 6, 8, 10 ]

Here's a example of generating a list of pairs [i*2, i*3].

# -*- coding: utf-8 -*-
# perl

use Data::Dumper;

@myList = map {[$_ * 2, $_ * 3]} (1..5);

print Dumper(\@myList); # [ [ 2, 3 ], [ 4, 6 ], [ 6, 9 ], [ 8, 12 ], [ 10, 15 ] ]

Here's a example of generating a nested list involving 2 looping variables that's normally done with “list comprehension”. In Perl, it's just done with normal nested loops.

# -*- coding: utf-8 -*-
# perl

@myList=();
for $i (1..5) {
  for $j (1..3) {
    push @myList, [$i,$j];
  }
}

use Data::Dumper; $Data::Dumper::Indent=0;
print Dumper(\@myList);

__END__

[
 [1,1],[1,2],[1,3],
 [2,1],[2,2],[2,3],
 [3,1],[3,2],[3,3],
 [4,1],[4,2],[4,3],
 [5,1],[5,2],[5,3]
]

If you have a question, put $5 at patreon and message me.

Perl

  1. Perl Overview
  2. Version String
  3. Help System

Detail

  1. Quoting String
  2. Format String
  3. String Operations
  4. True, False
  5. if then else
  6. Loop
  7. List / Array
  8. Loop Thru List
  9. Map f to List
  10. List Comprehension
  11. Hash Table
  12. Function Optional Param
  13. regex

Text Processing

  1. Unicode 🐪
  2. Convert File Encoding
  3. Read Write File
  4. Traverse Dir
  5. Find Replace
  6. Validate Local Links
  7. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. Sort Unstable
  4. Sort Misc
  5. List Modules, Search Paths
  6. Write a Module
  7. Complex Numbers
  8. System Call
  9. gzip
  10. Get Env Var
  11. GET Web Content
  12. Email