Mara55789
Mara55789

Reputation: 19

How to exclude hostnames in Perl

I'm very unfamiliar with perl syntax and am trying to amend an existing script to exclude a specific hostname from the results.

The hostnames are:

router-<something>
switch-<something>

I'd like to exclude all results that begin with "router" from the results.

This line in the existing script states:

    # These are hosts that we don't want to alert about.
    my %exclude_hosts = map { $_ => 1 } split(',', $exclude_hosts || '');

So two questions:

  1. Im trying to understand what "map" does in perl and what map { $_ => 1 }specifically does

  2. How would I insert logic into that statement to exclude all hosts that begin with "router"?

Upvotes: 0

Views: 68

Answers (1)

zdim
zdim

Reputation: 66964

That line builds a look-up table, where for each host there is a trivial (1) entry.

The map builtin takes a list and generates the output list by running the code in the block for each element, available in the special variable $_. The return of the last evaluated statement in the block for each element, what may be one or multiple scalars (or none), is flattened into the list that is eventually returned.

Here you get a pair for each element, the element itself $_ and 1 (the => operator is a , that quotes its left-hand side operand). An even-sized list can be assigned to a hash (dictionary), whereby successive elements become key-value pairs. So each host (in $_) becomes a key, with a value 1.

Then, to exclude an element either filter the list given to the map using grep

my %exclude_hosts = 
    map { $_ => 1 } 
    grep { not /^router/ } 
    split(',', $exclude_hosts || '');

or do this in map itself

my %exclude_hosts = 
    map { (not /^router/) ? $_ => 1 : () } 
    split(',', $exclude_hosts || '');

where the empty list () gets flattened in the map's returned list, thus vanishing.

Please see the linked documentation for more detail.

Upvotes: 1

Related Questions