Sunday, 8 February 2015

PERL - Tutorial Part 1 - ElecDude


           
PERL is a family of high-level, general-purpose, interpreted, dynamic programming languages. PERL is short for "Practical Extraction and Report Language". Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Perl is a programming language developed especially designed for text processing. It stands for Practical Extraction and Report Language. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. 
            Since then, it has undergone many changes and revisions. The Perl languages borrow features from other programming languages including C, shell scripting (sh), AWK, and sed. They provide powerful text processing facilities without the arbitrary data-length limits of many contemporary Unix command line tools, facilitating easy manipulation of text files. Perl 5 gained widespread popularity in the late 1990s as a CGI scripting language, in part due to its string parsing abilities.
            According to Wall, Perl has two slogans. The first is "There's more than one way to do it", commonly known as TMTOWTDI. The second slogan is "Easy things should be easy and hard things should be possible".

FEATURES:
            The overall structure of Perl derives broadly from C. Perl is procedural in nature, with variables, expressions, assignment statements, brace-delimited blocks, control structures, and subroutines.
            Perl also takes features from shell programming. All variables are marked with leading sigils, which allow variables to be interpolated directly into strings. However, unlike the shell, Perl uses sigils on all accesses to variables, and unlike most other programming languages which use sigils, the sigil doesn't denote the type of the variable but the type of the expression. So for example, to access a list of values in a hash, the sigil for an array ("@") is used, not the sigil for a hash ("%"). Perl also has many built-in functions that provide tools often used in shell programming (although many of these tools are implemented by programs external to the shell) such as sorting, and calling on operating system facilities.
            Perl takes lists from Lisp, hashes ("associative arrays") from AWK, and regular expressions from sed. These simplify and facilitate many parsing, text-handling, and data-management tasks. Also shared with Lisp are the implicit return of the last value in a block, and the fact that all statements have a value, and thus are also expressions and can be used in larger expressions themselves.
            Perl 5 added features that support complex data structures, first-class functions (that is, closures as values), and an object-oriented programming model. These include references, packages, class-based method dispatch, and lexically scoped variables, along with compiler directives (for example, the strict pragma). A major additional feature introduced with Perl 5 was the ability to package code as reusable modules. Wall later stated that "The whole intent of Perl 5's module system was to encourage the growth of Perl culture rather than the Perl core."
            All versions of Perl do automatic data-typing and automatic memory management. The interpreter knows the type and storage requirements of every data object in the program; it allocates and frees storage for them as necessary using reference counting (so it cannot de-allocate circular data structures without manual intervention). Legal type conversions — for example, conversions from number to string — are done automatically at run time; illegal type conversions are fatal errors.


The most up-to-date and current source code, binaries, documentation, news, etc. is available at the official website of Perl: http://www.perl.org/

Perl documentation is available in : http://perldoc.perl.org

Windows versions are available in

To find out the version of PERL in Command prompt type the following & press enter.
perl -v
This will display the information of installed PERL version.

DATA TYPES:
            Many of Perl's syntactic elements are optional. Rather than requiring you to put parentheses around every function call and declare every variable, you can often leave such explicit elements off and Perl will figure out what you meant. This is known as Do What I Mean, abbreviated DWIM. It allows programmers to be lazy and to code in a style with which they are comfortable.

            Perl is loosely typed language and there is no need to specify a type for your data while using in your program. The Perl interpreter will choose the type based on the context of the data itself.

            Perl has three basic data types: scalars, arrays and hashes.

COMMENTS:
            Text starting from a "#" character until the end of the line is a comment, and is ignored.

SCALAR:
            A scalar is the simplest kind of data that Perl manipulates. They are preceded by a dollar sign ($). A scalar is either a number, a string, or a reference. A reference is actually an address of a variable which we will see in upcoming chapters.  
            A scalar value can be acted upon with operators (like plus or concatenate), generally yielding a scalar result. A scalar value can be stored into a scalar variable. Scalars can be read from files and devices and written out as well.

            A number can be an integer number or a float. All are stored as C double precision float numbers internally. A number can be specified as decimal, octal, hexadecimal. All numbers are accessible as strings also. By default, all the numbers are stored and processed as DECIMAL only. To print in Hexa, Octal, Binary, scientific PRINTF() has to be used.
12                    : integer
-2348               : integer –ve

3.1412             : float number
-23.5e-4           : float number –ve

017                  : octal number
-017                 : octal number -ve

0x8AE              : hexadecimal number
-0x12F             : hexadecimal number –ve

0b011011            : binary number
-0b011011            : binary number –ve

Printing Formated Numbers:
printf("\n\n Hexa: %x",0x10);
printf("\n\n Binary: %b",0b101);
printf("\n\n Octal: %o",017);
printf("\n\n Scientific1: %f",1.6201e-4);
printf("\n\n Scientific1: %g",1.6201e-4);
printf("\n\n Scientific3: %.3g",1.6201e-4);
printf("\n\n Scientific4: %e",1.6201e-4);
printf("\n\n Scientific5: %.3e",1.6201e-4);


            Strings are sequences of characters (like hello). Each character is an 8-bit value from the entire 256 character set. They are usually alphanumeric values delimited by either single (') or double (") quotes.
            A double-quoted string literal allows variable interpolation, and single-quoted strings are not. There are certain characters when they are preceded by a back slash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Whereas anything within the single quoted string literal are treated as character only.
$doubleq= "Welcome!! \nThis is a new line.";  # interpolated
print $doubleq;
Result is:
Welcome!!
This is a new line.

$singleq= 'Welcome!! \nThis is a new line.'; # NO INTERPOLATION
print $singleq;
Result is:
Welcome!! \nThis is a new line.

Another example for interpolation:
$a=10.6;
$b="$a";  #now b=10.6=a -> interpolated
$c='$a'; #now c is a string with value '$a' -> NO INTERPOLATION

ARRAY:
            A array is a group of ordered scalar data. They are preceded by a 'at' sign (@). Each element of the array is a separate scalar variable with an independent scalar value. These values are ordered; that is, they have a particular sequence from the lowest to the highest element. 
            Arrays can have any number of elements. The smallest array has no elements, while the largest array can fill all of available memory.
Eg:
@num_array= (1,5,7,8,2.7,34e-12);
@str_array=("chara", "charc" , "charf");
@str_array_easy=qw( chara charc charf); #same as previous line @str_array

@mixed=($my_var, 3.1412, "input string", 0x125a, $a1+$a2);

@array1= (0 .. 10); # this will create an array with numbers starting from 0 to 10
@array2=('a' .. 'g'); # this will create an array starting from a to g

Working with Arrays:
@days=qw(Sun Mon Tue Wed Thu Fri Sat);
#get array size
$size= scalar (@days);
$size1= @days;
#get 1st element
$day1=$days[0];
($day1_1)=@days;
#get 3rd element
            $ele3=$days[2];
#get 1st & 2nd
$ele1=ele2=@days;
#get 4,5,2 to a new array
@newarr=@days[4,5,2];
#Clearing the array
            @newarr=(); #now the array has no elements
#remove the last element
            $lst=pop(@days);
#add elements to an existing array
            push(@days,($lst,"new")); #$lst & new are added to @days at the end


HASH:
            A hash is like the array which it is a collection of scalar data, with individual elements associated with index value. Unlike a list array, the index values of a hash are not small non negative integers, but instead are arbitrary scalars. These scalars, which are called keys, are used later to retrieve the values from the array and the element associated by keys are called values.  The elements of a hash have no particular order. A hash variable name starts with percent sign (%).
Syntax:
%hash1= ('key1','val1', ..., 'keyx','valx');
%hash2= ('key1'=>'val1', ..., 'keyx'=>'valx');
Note that key and value can have number, character or string.

Working with Hashes:
%hash2= ('key1'=>1, 'key3'=>3, 'key2'=>2, 'key'=>0);
@keys1= keys %hash1; #extract the KEYS
@values1= values %hash1; #extract the VALUES
#get the hash size
$size= @keys1;
$size2= @values1;  #$size=$size2

#get an element
$element=@hash1{'key2'};

#add a new hash pair
$hash1{55}='new_val';
$hash1{'new'}=100;

print "\n\nFormatted Hash";
@keys1= sort keys %hash1; #extract KEYS from hash1 & SORT in ascending order
foreach (@keys1){
            print "\n\t$_\t=> $hash1{$_}";
}          


PERL Example Program (Click here to download):
use warnings; #displays the warnings of the code.
print "\tThis is an PERL Example Program by ElecDude";
#create a new variable
$my_string="\nMy first PERL Program....";
#print the variable
print $my_string;



How to execute PERL Program:

  1. Open Command Prompt.
  2. Change the directory, where the PERL code is placed.
  3. Type the filename.pl and press enter.
  4. The results will in the window.
  5. If not, type as perl filename.pl  this would work.
Reactions:

0 comments:

Post a Comment

Search Here...