• 1

    ..

  • 2

    ...

  • 3

    ...

Showing posts sorted by relevance for query PERL. Sort by date Show all posts
Showing posts sorted by relevance for query PERL. Sort by date Show all posts

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.

Saturday, 12 March 2016

Perl Regular expression - Perl RegEx with examples

   A regular expression or RegEx is a string of characters that define the pattern or patterns you are viewing. The syntax of regular expressions in Perl is very similar to what you will find within other regular expression, supporting programs, such as sedgrep, and awk


   In this post, Perl regex is illustrated with examples.


Monday, 14 March 2016

Perl string manipulation with examples


  Perl offers many easier ways to manipulate string, which is yet powerful with RegEx. In this post, the various functions available in Perl for string manipulation is explained with examples. 

Monday, 2 November 2015

PERL TUTORIAL PART 4 - Working with files

FILE HANDLING


     The basics of handling files are simple, just associate a filehandle with an external file and then use a variety of operators and functions within Perl to read and update the data stored within the data stream associated with the filehandle. The filehandle is the name for an I/O connection between the Perl process and the outside world.
     A filehandle is a named internal Perl structure that associates a physical file with a name. The mode of operation must be specified for the filehandle is opened.
     Three basic file handles are - STDIN, STDOUT, and STDERR which represent standard input, standard output and standard error devices respectively. Apart from these, any number of filehandles can be added in the code.
The different file operations are:
1) Opening a file
2) Closing the file
3) File Reading
4) File Writing
5) File tests

1) Opening a file

The syntax for opening a file is as follows:
open(FILEHANDLE,"<mode>file_name");
or simply
open(FILEHANDLE,"mode","file_name");
where mode specifies the type of file access.
MODE SYMBOL
ACCESS TYPE
< or r
Read Only Access
> or w
Creates, Writes, and Truncates
>> or a
Writes, Appends, and Creates
+< or r+
Reads and Writes
+> or w+
Reads, Writes, Creates, and Truncates
+>> or a+
Reads, Writes, Appends, and Creates
Most commonly used are <, >, >>.
It is a good practice to use capital letters for filehandles. And for safe operation, it is always recommended to use the DIE(....) function for file open which will terminate the program when it fails to open the file.
open(FILEHANDLE,"mode","file_name") or die "Unable to open the file(file_name)";

Example:
open(FH1R,"<","file1.txt") or die "Unable to open the file(file1.txt) in read mode!";
open(FH2W,">file2.txt") || die "Unable to open the file(file2.txt) to write!";
$logfilename="log.txt"
open(LOG,">>",$logfilename) || die "Unable to open the file(log.txt) in append mode!!!";

2) Closing the file

To close a file simply call the CLOSE(...) function with the filehandle as input. All the filehanldes are automatically closed when the Perl program terminates. The syntax is
close(FILEHANDLE);

3) Reading from a file

To read the contents from the file, <> operator is used, just like STDIN.
Example:
$line_1=<FH1R>; #reads only one line
@lines=<FH1R>; #reads the entire file, & places in the array

4) Writing to a file

Writing data to a file is simply like printing to STDOUT, except the filehandle is used between the print keyword & data.
Example:
print FH2W "Hello!! This is 1st line...\n";

5) File testing

File tests are performed on file handles to determine the file properties. For example –e FileHandle returns true if the file pointed by FileHandle exists in the system. The below table shows the different file test that can be performed in Perl. Note that the CAPITAL and small letter tests produces different results.
PARAMETER
DESCRIPTION
-r
File or directory is readable
-w
File or directory is writable
-x
File or directory is executable
-o
File or directory is owned by user
-R
File or directory is readable by real user, not effective user
(differs from -r for setuid programs)
-W
File or directory is writable by real user, not effective user
(differs from -w for setuid programs)
-X
File or directory is executable by real user, not effective user
(differs from -x for setuid programs)
-O
File or directory is owned by real user, not effective user
(differs from -o for setuid programs)
-e
File or directory exists
-z
File exists and has zero size (directories are never empty)
-s
File or directory exists and has nonzero size (the value is the size in bytes)
-f
Entry is a plain file
-d
Entry is a directory
-S
Entry is a socket
-p
Entry is a named pipe (a "fifo")
-t
isatty() on the filehandle is true
-T
File is "text"
-B
File is "binary"
-c
Entry is a character-special file
-M
Modification age in days
-A
Access age in days
-C
Inode -modification age in days

Example:
if (-e FH1)
print "File FH1 exists\n";
if (-T FH1)
print "File FH1 exists & is a Text file\n";
$size= -s FH1;
print "File size is $size bytes...\n";
We welcome your valuable comments and suggestion.
It helps us to do better in future.
Thank you.

Thursday, 19 February 2015

PERL TUTORIAL PART 3 – ELECDUDE

PERL TUTORIAL PART 3 – ELECDUDE

In this, lets go through the different control structures available in Perl and its examples.

Click here to goto Tutorial Part 1.

Click here to goto Tutorial Part 2.

CONTROL STRUCTURES IN PERL:

               Perl has different control structures, which are as follows:
·       The if/unless Statement
·       The while/until Statement
·       The for Statement
·       The foreach Statement





if  Statement:
            This construct takes a control expression (evaluated for its truth) and a block. It may optionally have an else followed by a block as well.  It is similar to C language.
Syntax:
if (<expression>) {
true_statement; #executes if expression is true
.....
true_statementn;
} else {
false_statement; #executes if expression is FALSE
.....
false_statementn;
}

Another form of IF is the if...elsif...else statement , which has multiple expressions & statements.
Syntax:
if (<expression1>) {
true_statement1; #executes if expression1 is true.
.....
true_statementn1-n;
} elsif (<expression2>) {
true_statement2; #executes if expression1 is false & expression2 is true.
.....
true_statement2-n;
}else {
false_statement1; #executes is both the above expressions are false
.....
false_statementn;
}

unless Statement:
            This construct takes a control expression (evaluated for its falseness) and a block. It may optionally have an else followed by a block as well.  It is same as if statement executing a false condition.
Syntax:
unless (<expression>) {
false_statement; #executes if expression is FALSE
.....
false_statementn;
} else {
true_statement; #executes if expression is true
.....
true_statementn;
}

Another form of IF is the unless...elsif...else statement , which has multiple expressions & statements.
Syntax:
unlsess (<expression1>) {
false_statement1; #executes if expression1 is false.
.....
flase_statementn1-n;
} elsif (<expression2>) {
true_statement2; #executes if expression1 is ture & expression2 is true.
.....
true_statement2-n;
}else {
false_statement1; #executes is both the above expression1 is true & 2 is false
.....
false_statementn;
}

Examples:
$a=5;
if($a==20) {
      printf "\ta is equal 20.\n";
} elsif ( $a < 20 ){
      printf "\ta is less than 20.\n";
}
else {
      printf "\ta is not less than nor equal to 20.\n";
}

unless($a==20) {
      printf "\ta is equal 20.\n";
} elsif ( $a < 20 ){
      printf "\ta is not less than 20.\n";
} else {
      printf "\ta is less than 20.\n";
  }

Loop statements:
            Perl can iterate using the while statement The FOR, FOREACH and WHILE are also known as loop statements, as these repeatedly execute a block of statements for a specific condition.
 WHILE statement executes the statement block till the expression returns TRUE.
while (expression) {
statement_1;
statement_2;
statement_n;     
  }
DO.. WHILE is similar to that of WHILE, but the condition is evaluated at the end of execution of block statements. This is similar to C language. The difference between WHILE & DO WHILE is that, in DO WHILE loop the block of statements is executed once regardless the result of expression.
do{
statement_1;
statement_2;
statement_n;     
} while (expression;

 The UNTIL executes the block of statements till the expression returns FALSE. Replacing the while with until yields the desired effect.
until (expression) {
      false_statement_1;
      false_statement_2;
false_statement_n;
  }

Examples:
$a = 10;
### while
while( $a < 20 ){
   printf "Value of a: $a\n";
   $a = $a + 1;
}
### do..while
$a = 13;
do{
   printf "Value of a: $a\n";
   $a = $a + 1;
}while( $a < 13 );
printf "Now Value of a: $a\n";
### until
$a = 5;
until( $a > 10 ){
   printf "Value of a: $a\n";
   $a = $a + 1;
}

for Statement is another Perl iteration construct, which looks like C or Java's for statement.
Syntax is:
for ( initialise; expression; update ) {
statement1;
statement2;
...
statementn;
}
Example:
for( $a = 10; $a < 20; $a=$a+1 ){
      print "value of a: $a\n";
}

            The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. The foreach keyword is actually a synonym for the for keyword, so you can use either. If VAR is omitted, $_ is set to each value.

Syntax:
foreach VAR (VAR) {
   statement1;
   ...
   statementn;
}
##
foreach $local (@array1) {
   $local has the elements of @array1 each for every iteration
}
##
foreach (@array1) {
   $_ has the elements of @array1 each for every iteration
}
##
for $local (@array1) {
   $local has the elements of @array1 each for every iteration
}

Example:
@list = (2, 20, 30, 40, 50);
foreach $a (@list){ #$a is local to the loop only
      print "value is: $a\n";
}

my $b=123;
for $b (@list){
#$b is local to the loop with @list contents only, & the former global value of $b not accessible within the loop.
      print "value is: $b\n";
}
#$b regains the value 123.

@list = (2, 20, 30, 40, 50);
foreach my $a (@list){ #$a is local to the loop only
      print "value is: $a\n";
}
print "\na= $a";

my $b=12345;
print "\nb= $b\n\n";
for $b (@list){ #$b is local to the loop & becomes global on loop exit
      print "value is: $b\n";
}
print "\nb= $b";


We welcome your valuable comments and suggestion.
It helps us to do better in future.
Thank you.


Search Here...