Tuesday 27 December 2016

Using postfix conditionals and loops in perl

Conditional & loop statements are a standard & integral part of any programming language. These type of statements follow a somewhat standard syntax. In case of a conditional statement we write a statement to have the condition checked & another statement performing an action based on the result of the condition. In case of a loop statement we first write a statement for defining the loop i.e. the conditions under which the loop will continue to iterate followed by the action performed as a result of the loop execution.

Perl offers a non-standard unique feature of defining the action to performed before mentioning the condition/loop statement. Although this is valid only when the conditional/loop block does not span more than a single statement i.e. we are performing a single action like printing the contents on an array via a foreach loop.

Here is a sample code demonstrating various usage examples for postfix conditional & loop statements along with an example for last & next statement as well.

The next statement is used to skip a match within the loop & the last statement terminates the loop when the match if found.

[root@cent6 ~]# cat post.pl
#!/usr/bin/perl -w
#
my @art = ("one", "two", "three", "four", "five") ;

print "postfix foreach example \n";
print "$_ \n" foreach (@art) ;

print "postfix if example \n";

my $a = 10;
my $b = 20;

print "true \n" if ($a < $b) ;

print "postfilx while example \n" ;

my @art2 = qw (unix linux debian) ;

print shift @art2, "\n"  while (@art2) ;

print "postfix next & last example \n" ;

my @art3 = qw (1 2 3 4 5 6 7 8) ;

print "next statement example \n" ;

foreach (@art3) {
        next if ($_ == 2) ;
        print "$_ \n" ;
        }

print "last statement example \n" ;

foreach (@art3) {
        last if ($_ == 4) ;
        print $_, "\n" ;
        }


The above script shows the following output when executed:

[root@cent6 ~]# ./post.pl
postfix foreach example
one
two
three
four
five
postfix if example
true
postfilx while example
unix
linux
debian
postfix next & last example
next statement example
1
3
4
5
6
7
8
last statement example
1
2
3
[root@cent6 ~]#


This may not sound very useful at first but it can help make your perl scripts significantly shorter when used appropriately.

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...