Tuesday 5 September 2017

Using ternary operator in perl

Today I'd like to share a quick script with 2 examples on using the ternary operator in perl and another quick trick to get file size in perl.

Here's the script:

#!/usr/bin/perl -w

my $dir="/root" ;
my $script="ternary.pl";

if (-e $dir) {
if (-d _ ) {  print "$dir exists \n"; }

if (-s $script ) { $size= -s $script; print "$script is not empty and size is $size bytes \n";}

}


print $dir?"file exits\n":"File does not exist \n";

$a=10;$b=20;
$c = $a < $b ? $a:$b;

print "$c \n";


If I assign the -s <file_name> expression which returns true if a file is not empty to an scalar variable then that variable will have the size in bytes of the file being tested.

Moving out of the nested if statements we move to the ternary operator whose syntax is:

expressions?statement1:statement2

So this executes statement1 if expression is true and it executes statement2 if expression is not true.

From experience I've observed that the ternary operator expression tests hold good for numeric tests and does not work with file related tests.

The ternary operator is useful when you'd like to replace simple and short if-else statements with a single statement.

Executing the script gives the following result:

[root@pbox scripts_pl]# ./ternary.pl
/root exists
ternary.pl is not empty and size is 323 bytes
file exits
10

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