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.


PERL TUTORIAL PART 2 – ELECDUDE

            We hope you've gained the basic PERL knowledge from our Tutorial Part 1. In this part, let's go through about the PERL's basic input output, operators and its examples.

Click here to goto Tutorial Part 1.

BASIC I/O:

Input from STDIN
  Reading from standard input is easy, via the Perl file handle called STDIN. It returns the entire line content into a scalar variable.
$a = <STDIN>;  #the contents of input STDIN line is stored in $a
  To store many lines in the variable, the array variable is used.
@arr = <STDIN>; #the contents of each input STDIN line is stored in each element of @arr
  Note that STDIN always returns along with the NEW LINE character ie \n. To remove the new line, chomp() function is used.
$a = <STDIN>;  #the contents of input STDIN line with \n
Chomp($a); #the new line is removed.

Output to STDOUT
  Sending values to Standard Output is also easy, via the Perl file handle called STDOUT. The keyword used for this is PRINT/PRINTF
print "Hello!!";
print ("Hello!!");
print "Hell","o!!";
printf("%s","Hello!!"); #just like C language.
  All the above statement displays the same result. Arithmetic operations are also performed in the print statements.
$a=4;
print $a+$a; #prints 8
print ($a," Hello!!"); #prints 4 Hello!!
printf("%s-%d","Hello!!",$a*3); #just like C language. prints Hello!!-12

  Often printf statement is used for printing formatted text.


OPERATORS:

Perl language supports many operator types but following is a list of important and most frequently used operators:
·       Arithmetic Operators
·       Equality Operators
·       Logical Operators
·       Assignment Operators
·       Bitwise Operators
·       Logical Operators
·       Quote-like Operators
·       Miscellaneous Operators

Arithmetic Operators
Operator
Description
+
Addition - Adds values on either side of the operator
-
Subtraction - Subtracts right hand operand from left hand operand
*
Multiplication - Multiplies values on either side of the operator
/
Division - Divides left hand operand by right hand operand
%
Modulus - Divides left hand operand by right hand operand and returns remainder
**
Exponent - Performs exponential (power) calculation on operators
Equality/relational Operators
Operator
Description
==
Checks if the value of two operands are equal or not, if yes then condition becomes true.
!=
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
<=>
Checks if the value of two operands are equal or not, and returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument.
> 
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
< 
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
Equality Operators for Strings
Operator
Description
lt
Returns true if the left argument is stringwise less than the right argument.
gt
Returns true if the left argument is stringwise greater than the right argument.
le
Returns true if the left argument is stringwise less than or equal to the right argument.
ge
Returns true if the left argument is stringwise greater than or equal to the right argument.
eq
Returns true if the left argument is stringwise equal to the right argument.
ne
Returns true if the left argument is stringwise not equal to the right argument.
cmp
Returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument.
Assignment Operators
Operator
Description
=
Simple assignment operator, Assigns values from right side operands to left side operand
+=
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
-=
Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
/=
Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
%=
Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
**=
Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand
Bitwise Operators
Operator
Description
&
Binary AND Operator copies a bit to the result if it exists in both operands.
|
Binary OR Operator copies a bit if it exists in eather operand.
^
Binary XOR Operator copies the bit if it is set in one operand but not both.
~
Binary Ones Complement Operator is unary and has the efect of 'flipping' bits.
<< 
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
>> 
Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.


Logical Operators
Operator
Description
and
Called Logical AND operator. If both the operands are true then then condition becomes true.
&&
C-style Logical AND operator copies a bit to the result if it exists in both operands.
or
Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.
||
C-style Logical OR operator copies a bit if it exists in eather operand.
not
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
Miscellaneous Operators
Operator
Description
.
Binary operator dot (.) concatenates two strings.
x
The repetition operator x returns a string consisting of the left operand repeated the number of times specified by the right operand.
..
The range operator .. returns a list of values counting (up by ones) from the left value to the right value
++
Auto Increment operator increases integer value by one
--
Auto Decrement operator decreases integer value by one
->
The arrow operator is mostly used in dereferencing a method or variable from an object or a class name


Quote-like Operators
Operator
Description
q{ }
Encloses a string with-in single quotes
qw{ }
Encloses a string with-in double quotes
qq{ }

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


           
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.

Search Here...

Loading...

Labels

materials (37) VLSI (33) embedded (26) jobs (24) avr (22) Govtjob (19) NONGOVT (19) Verilog codes (14) circuit ideas (12) vhdl (10) Ebook (9) elec softwares (7) PPT (6) c (5) circuit lab (5) projects (5) General (4) RESULTS (4) avr studio (3) gate (3) placements (3) 8051 self learn (2) Android (2) DIY (2) ISRO (2) SERIAL COMMUNICATION USING AVR ATMEGA8 (2) electronics (2) microcontroller (2) 24Vdc 3A - Voltage regulator - circuit schematic diagram (1) 555 calculator (1) 7 SEGMENT VLSI CODE (1) 8051 programmer serial port (1) 8051 tutorial part1 (1) 8051 tutorial part2 (1) ALU VLSI CODE (1) ANSWER KEY FOR GATE 2012 -GATE 2012 ANSWER KEY (1) APPLICATION ENGINEER -TRAINEE - Corel Technologies (1) AVR SPI (1) About MAX7219 display driver (1) Administrative Officers (Scale-I) - NATIONAL INSURANCE COMPANY LIMITED - ONLINE Recruitment (1) BOOTH MULTIPLIER (1) GROUP DISCUSSION - TECHNIQUES & TIPS (1) GUIDE LINE FOR FRESH ENGINEERING STUDENTS (1) IMAGE FILE TO TEXT FILE CONVERSION MATLAB – TEXT FILE TO IMAGE FILE CONVERSION MATLAB EXAMPLE (1) IMAGE PROCESSING IN VERILOG - ADD IMAGES IN VERILOG - MATLAB XILINX MODELSIM (1) MODELSIM TUTORIAL – WORKING WITH TESTBENCH – GETTING STARTED (1) MatLab Programs - IMPULSE - STEP - SINE - COSINE -TRIANGULAR - SAWTOOTH - EXPONENTIAL SIGNALS GROWING DECAYING (1) Microchip (1) QUALITIES AND PERSONALITIES FOR GOOD PERSON & SOME EMPLOYEE AND GET HIRED (1) SPI Working Modes of Operation - Verilog Code - Applications - Advantages Disadvantages (1) SPI verilog code master code slave code testbench. (1) Simple CGPA Calculator for Engg Colleges Anna university (1) TRAFFIC LIGHT CONTROLLER VLSI CODE (1) TRANSISTOR CODES AND CHOOSING (1) Tanner tutorial P1 (1) UNIVERSAL SHIFT REG VHDL CODE (1) VCD Description - Export VCD in Xilinx Modelsim - Example (1) XILINX 13.2 TUTORIALS (SELF LEARNING MATERIAL ) (1) avr calculator (1) avr serial header (1) chat (1) vhdl image processing add image (1)