Saturday, April 3, 2021

Perl Commands: Reference Sheet

Here are some important Perl commands and constructs that are commonly used in Perl scripts to serve as a reference.

In this cheatsheet version of Perl commands, syntax is not explained in detail. Just the command and common usage format of the command is provided with no particular order as such.

For complete information on the commands and formats, refer the Perl documentation.

Reference sheet of commonly used Perl commands:

Variable: $string = 1

Array:  @string = ('a','b','c')

Hash:

my %new = (
KEY1 => "value1",
KEY2 => "value2"
);

(Access the KEY1 value using $new{KEY1})

Print on screen:   print "text"

String equality:  $str1 eq $str2

Remove newline character \n from string: chomp $string

If-Else: 

if (cond1) {statements1;} 
elsif (cond2) {statements2;} 
else      {statements3;}

(Note that curly braces are required even for a single statement unlike C/C++)

While: while (cond) {}

Open file to read:  open ($filepointer'<''filename')

Open file to write:  open ($filepointer,'>','filename')

Close file:   close ($filepointer)

Pattern Matching:  $string =~ m/abc/

(To check if pattern 'abc' is found in $string)

Substitution operation:  $string =~ s/a/b/g;

(To substitute all occurrences of a with b in $string)

Substring from string:  $pattern = substr($string, 3, -3);

(To extract the substring after removing three characters from the left and right of $string)

Split string:  @string = split(/ /, $string, 2);

(To split $string into two at the occurrence of a space and store in array string)

Join string with pattern:   $string = join("-", $str1, $str2, $str3)

($string will be like this $str1-$str2-$str3)

Add element to end of array:   push (@array, $element)

Remove last element from array:   pop (@array)

Shift array to left by 1:   shift (@array)

Shift array to right by 1:   unshift (@array)

Get options from user:

use Getopt::Long;
$string = GetOptions ("opt1=s" => \$var1,
                      "opt2=s" => \$var2);

(This command gets two options opt1 and opt2 from the user and stores them in variables $var1 and $var2)

Reading data from config file:

Considering that the config.cfg file consists of data like this:
VAR1 = "value1"
VAR2 = "value2"

Then we can import this data into Perl program using:

use Config::General;
$conf = Config::General->new("config.cfg");
my %config = $conf->getall;

The config variable can be accessed from the Perl program using $config{VAR1}

Execute Linux commands using Perl: 

We can also execute Linux commands directly from a Perl script by enclosing the command within backticks ` `. Example:  `rm -f file` will perform the shell operation of removing the file.

No comments:

Post a Comment