Perl Cheatsheet

1307




Perl(Practical Extraction and Report Language) is especially designed for text processing by Larry Wall. Perl is a high level programming language and hence one can easily undertand Perl as the programs are in simple english.

Basics

Sample program

print "Hello World!!"; # to display "Hello World!!"
  • print -- to print the data given
  • # -- single line comments

Data types

Perl has three basic data types:

  1. Scalars
  2. Arrays
  3. Hashes
$var-name =value; #scalar-variable
@arr-name = (values); #Array-variables
%hashes = (key-value pairs); # Hash-variables 

In Perl, there is no need to explicitly declare variables to reserve memory space. When you assign a value to a variable, declaration happens automatically.

Operators

Operator typeDescription
Arithmetic Operator+ , - , * , / , %, **
comparision Operator< , > , <= , >=, != , ==
Bitwise Operator& , ^ , |, ~, <<, >>
Logical Operator&& , ||, !
Assignment Operator= , += , -= , *= , /= , %=, <<=, >>=, &=, ^=, |=
Quote Operatorq{ }, qq{ }, qx{ }

String Functions

Below are some of the useful string functions in Perl.

String FunctionDescription
lengthThis function is used to return the number of characters of a given string
substrThis method is used to modify a substring in a string
indexSearches for a substring in the given string and returns the position of the first occurrence of the substring if found
rindexSimilar to index but searches for a substring from right to left
reverseThis function is used to reverse a string
lcThis function is used to convert the specified string to lowercase
ucThis function is used to convert the specified string to uppercase
cryptThis function is used to encrypt password
q/string/used to create single-quoted strings
qq/string/used to create double-quoted strings
chrto return ASCII or UNICODE character of a number
hexused to convert a hexadecimal string to it's equivalent decimal value
octused to convert an octal number to it's equivalent decimal value
ordreturns the ASCII value of the first character of a string
sprintfFormats string provided by the user and returns the formatted string to be used with print()

Lists

List is a series of scalar values separated by commas and enclosed in round brackets. Lists are immutable.

(); # empty list

(1,2,3,4,5); # integer list

("Hello", "World"); #string list

("happy", 16) # list with different types of data

Hashes

Hash is an unordered set of key/value pairs. They are preceded by %.

%nationalGame = (Australia => 'Cricket',
Japan => 'Wrestling',
NewZealand => 'Rugby',
USA => 'Baseball',
England => 'Cricket');

Arrays

Array is a variable which gives dynamic storage for a list.

my @fruits = qw(Apple Orange Grapes Kiwi Watermelon Banana);

Array Operations

Array OperationsDescription
$countreturns the number of elements in the array
$#returns the highest index of an array
push()appends one or more elements to the end of an array
unshift()adds one or more elements to the front of the array
pop()removes the last element from the end of an array
sort()used to sort an array in alphabetical or numerical order.

Conditional Statements

1. If

if(conditional-expression)
{
    #code
}

2. If-else

if(conditional-expression)
{
    #code
} else {
    #code
}

3. If-else-if ladder

if(conditional-expression-1)
{
    #code
} elsif(conditional-expression-2) {
    #code
} elsif(conditional-expression-3) {
    #code
}
....
else {
    #code
}

4. Nested-If

Nested-Ifs represents if block within another if block.

if(conditional-expression-1) {    
     #code    
          if(conditional-expression-2) {  
             #code
             if(conditional-expression-3) {
                 #code
             }  
    }    
}

5. Unless

Unless is similar to If and is equivalent to if-not.

statement unless(condition-expression);

#or

unless(condition-expression){
   #code 
}

6. Unless-else

unless(condition-expression){
  # unless code
}else{
  # else code
}

7. Given

Given is similar to Switch in other programming languages.

given(conditional-expression){    
when(value1){#code}
when(value2){#code}
when(value3){#code}
...
} 

Loops

1. For

for(Initialization; Condition; Increment/decrement){  
#code  
} 

#or

for (range){
  #code
}

2. While

while(condition){  
#code 
}  

3. Do-while

do{  
#code 
} while(condition); 

4. Until

until(conditional-expression){
   # code
}

5. Do-Until

do{
   # code
}until(condition-expression)

Classes and Objects

Class

package className; 

Objects

$object = new className( Attributes);

Methods

sub methodName{
  #code
}

Sub-routines

sub SubName  [PROTOTYPES] [ATTRIBUTES] { # defining a sub-routine
  #code
}

&SubName; # calling a sub-routine
#or
SubName(argument-list); # calling a sub-routine, argument-list is optional

Example

sum(10,20);

sub sum() {
   $sum = 0;

   foreach $item (@_) {
      $sum += $item;
   }
print "sum is: $sum"
  
}

Files

Opening a file

open(filehandle,mode,filename)
ModeSymbol
read<
write>
append>>

Example

open(FH, '<', 'c:\sample.txt');

Closing a file

close(FH);
File test OperatorDescription
-rchecks if the file is readable
-wchecks if the file is writable
-xchecks if the file is executable
-ochecks if the file is owned by effective uid.
-Tchecks if the file is an ASCII text file.
-Bchecks if the file is a binary file.
-echecks if the file exists.
-zchecks if the file is empty.
-schecks if the file has nonzero size.
-fchecks if the file is a plain file.
-dchecks if the file is a directory.
-lchecks if the file is a symbolic link.
-pchecks if the file is a named pipe (FIFO.
-Schecks if the file is a socket.
-bchecks if the file is a block special file.
-cchecks if the file is a character special file.