Monday 4 September 2017

Using the each operator in Perl

The each operator can be used on array and hash variables in perl. The ability to use each on an array has been added to perl after version 5.12 and is not available in earlier versions.

Hash context:
When we use each on a hash, it returns a 2 element list containing the key and value pair in the hash.

Array context:
When used with an array, the each function returns a 2 element list containing the element value and it's corresponding index value within the array.

Given below is a small script to demonstrate this:

#!/usr/bin/perl -w

use 5.012;

my @array=qw/unix linux solaris/;

my %hash=("oracle" => "solaris", "redhat" => "RHEL");

while (my ($index, $element) = each @array) {
 say "$element is at index $index";
}

while (my ($key,$value) = each %hash) {
 say "$key has the value $value";
}


The output of the script is as follows:

unix is at index 0
linux is at index 1
solaris is at index 2
redhat has the value RHEL
oracle has the value solaris

Using perl version 5.12 allows us to use say in our script instead of print and its advantage is that say automatically inserts a newline in it's output unlike print where we have insert a \n manually.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...