Recently I found out that while using a nested if-else statement in perl we could substitute the variable name with underscore (_) in the substituent if conditional statements.
Here is a an example script:
#!/usr/bin/perl
my $file = "/tmp/file1.txt";
my (@description, $size);
if (-e $file)
{
push @description, 'binary' if (-B _);
push @description, 'a socket' if (-S _);
push @description, 'a text file' if (-T _);
push @description, 'a block special file' if (-b _);
push @description, 'a character special file' if (-c _);
push @description, 'a directory' if (-d _);
push @description, 'executable' if (-x _);
push @description, (($size = -s _)) ? "$size bytes" : 'empty';
print "$file is ". join(', ',@description)."\n";
}
Here is a an example script:
#!/usr/bin/perl
my $file = "/tmp/file1.txt";
my (@description, $size);
if (-e $file)
{
push @description, 'binary' if (-B _);
push @description, 'a socket' if (-S _);
push @description, 'a text file' if (-T _);
push @description, 'a block special file' if (-b _);
push @description, 'a character special file' if (-c _);
push @description, 'a directory' if (-d _);
push @description, 'executable' if (-x _);
push @description, (($size = -s _)) ? "$size bytes" : 'empty';
print "$file is ". join(', ',@description)."\n";
}
The first if condition checks if the file exists with the -e flag. Notice that after using the variable name in the outer if statement, I was able to substitute it with _ for the inner if condition tests.
The nested if statements test for various attributes of the file and append a string at the end of an array named description if the attribute being tested for returns true.
Finally we modify the array being used into a string using the join function and print it out.
The file being used here exists so executing the script yields the following results:
[root@pbox scripts_pl]# ls -l /tmp/file1.txt
-rw-r--r--. 1 root root 16 Sep 5 06:51 /tmp/file1.txt
[root@pbox scripts_pl]#
[root@pbox scripts_pl]# ./describe.pl
/tmp/file1.txt is a text file, 16 bytes
No comments:
Post a Comment