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.

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
#       };

Filter a list using grep in Perl

Answer:

The Perl's grep function is very useful for list filtering.

E.g. Array filtering

my @new = grep {$_ > 1} (1,2,3);

# @new contains 2, 3 only

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.

Array reference in Perl

Answer:

Array reference is something like a pointer to a array data structure in Perl

Example:

use strict;
use warnings;

my @a = (1, 2, 3);

my $array_ref = \@a;

$a[2] = "foo";

print $array_ref->[2];    # print out "foo" as change in  @a will also be reflected in its reference

Hash reference in Perl

Answer:

Hash reference is something like a pointer to a hash data structure in Perl

Example:

my %hash = (
        "a" => "1",
        "b" => "2",
);

my $hash_ref = \%hash;

$hash{"a"} = "A";

print $hash_ref->{"a"}; # print out "A" as change in  %hash  also reflected in its reference