Perl: Map Function to List

By Xah Lee. Date:

Map Function to List

Use map to apply a function to a list.

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

use Data::Dumper; $Data::Dumper::Indent=0;

sub ff {return $_[0] + 1;};

print Dumper [ map { ff $_ } (1,2,3,4)]; # → [2,3,4,5];

# ff written as embedded expression
print Dumper [ map { $_ + 1 } (1,2,3,4)]; # → [2,3,4,5];

The (0..10) generate a list from 0 to 10.

The % above is the operator for computing remainder of a division.

The Data::Dumper module is to import the “Dumper” function for printing list.

Removing Elements in a List

Use grep to remove elements in a list.

Example:

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

use Data::Dumper;

sub ff {return $_[0] % 2 == 0}; # return true if divisible by 2

print Dumper[ grep {ff $_} (0..10)]; # ⇒  [ 0, 2, 4, 6, 8, 10 ]

Here's the same thing, where the function is embedded as a expression:

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

use Data::Dumper;

print Dumper[ grep {$_[0] % 2 == 0} (0..10) ]; # ⇒  [ 0, 2, 4, 6, 8, 10 ]

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