Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Sep 102010
 

Generate new list using map in Perl

Answer:

The Perl's map function is superb cool for generating new list based on an existing list.

1. Generate new array based on an existing array

my @new = map {$_ * 2} (1, 2, 3);

# @new contains 2, 4, 6

2. Generate new hash based on an existing array

my %new = map {$_ => 1} (1,2,3);

# %new contains a hash...
#      {
#           '1' => 1,
#           '3' => 1,
#           '2' => 1
#       };


Sep 022010
 

Simple try catch block in Perl

Answer:

Perl don't have try/catch statement by default, but you can simulate using the following way:

eval {
    print 1/0;
};

if ($@) {
    print "Error message: $@";
};

When executed, it shows:

Error message: Illegal division by zero at test.pl line 7.