Perl While

advertisement
PERL
Ronald L. Ramos
Proglan
What is PERL?
• Perl stands for Practical Extraction and Reporting Language.
(or Pathologically Eclectic Rubbish Lister).
• Perl is a general-purpose, high level, interpreted and dynamic
computer programming language with a vast number of uses.
• PERL is a language for doing what you want to do
PERL Strengths
• Perl runs on all platforms and is far more portable than C.
• Perl and a huge collection of Perl Modules are free software
(either GNU General Public License or Artistic License).
• Perl is very much efficient in TEXT and STRING manipulation
i.e. REG_EXP.
• It is a language that combines the best features from many
other languages and is very easy to learn if you approach it
properly.
• Dynamic memory allocation is very easy in PERL, at any point
of time we can increase or decrease the size of the array.
PERL Weaknesses
• 1) You cannot easily create a binary image ("exe") from a Perl
file. It's not a serious problem on Unix, but it might be a
problem on Windows.
• 2) Moreover, if you write a script which uses modules from
CPAN, and want to run it on another computer, you need to
install all the modules on that other computer, which can be a
drag.
• 3) Perl is an interpretative language, so its comparatively
slower to other
compiling language like C. So, it s not feasible to use in Real
time environment like in flight simulation system.
Hello World
print "Hello World!\n";
VARIABLES
Scalar Variables
• Scalar data is the one of the most basic and simplest data in
Perl. Scalar data can be number or string.
• In Perl, string and number can be used nearly interchangeably.
• Scalar variables are used to hold scalar data. Scalar variables
start with dollar sign ($) followed by Perl identifier.
• Perl identifiers can contain alphanumeric characters and
underscores. You cannot start with a digit.
Numbers
#floating-point values
$x = 3.14;
$y = -2.78;
#integer values
$a = 1000;
$b = -2000;
Perl also accepts string literal as a number for example:
$s = "2000"; # similar to $s = 2000;
String
$str = "this is a string in Perl“;
$str2 = 'this is also as string too‘;
Operations on Scalars
$x = 5 + 9; #
$x
$x = 30 - 4;#
#
$x = 3 * 7; #
in $x
$x = 6 / 2; #
$x = 2 ** 8;#
$x = 3 % 2; #
$y = ++$x; #
$y = $x++; #
$y = --$x; #
$y = $x--; #
$x = $y;
#
$x += $y;
#
$x -= $y;
#
$x .= $y;
#
Add 5 and 9, and then store the result in
Subtract 4 from 30
and then store the result in $x
Multiply 3 and 7 and then store the result
Divide 6 by 2
two to the power of 8
Remainder of 3 divided by 2
Increase $x by 1 and store $x in $y
Store $x in $y then increase $x by 1
Decrease $x by 1 and then store $x in $y
Store $x in $y then decrease $x by 1
Assign $y to $x
Add $y to $x
Subtract $y from $x
Append $y onto $x
String Operations
$x = 3;
$c = "he ";
$s = $c x $x;
$b = "bye"; # $c repeated $x times
print $s . "\n"; #print s and start a new
line
# similar to
print "$s\n";
$a = $s . $b; # Concatenate $s and $b
print $a;
Scalar Interpolation
$x = 10;
$s = "you get $x";
print $s;
CONTROL STRUCTURES
Code blocks
A block is surrounded by a pair of curly braces and can be
nested within a block:
{ #statements here
{ # nested block
# statements here
}
}
If
If control structure is used to execute a block of code based on a
condition. The syntax of If control structure is as follows:
if(condition){
statements;
}
If the condition is true the statements inside the block will be
executed, for example:
$x = 10;
$y = 10;
if($x == $y){
print "$x is equal to $y";
}
If Else
If you need an alternative choice, Perl provides if-else
control structure as follows:
if(condition){
if-statements;
}
else{
else-statements;
}
If Else
If the condition is false the else-statements will be
executed. Here is the code example:
$x = 5;
$y = 10;
if($x == $y){
print "x is equal to y";
}
else{
print "x is not equal to y";
}
If Else If
Perl also provides if-else-if control structure to make
multiple choices based on conditions.
if(condition1){
}
else if(condition2){
}
else if(condition3){
}
...
else{
}
If Else If
Here is the source code example:
$x = 5;
$y = 10;
if($x >
print
}
else if
print
}
else{
print
}
$y){
"x is greater than y";
($x < $y){
"x is less than y";
"x is equal to y";
For
• In order to run a block of code iteratively, you use Perl
for statement.
• The Perl for statement is used to execute a piece of code
over and over again.
• The Perl for statement is useful for running a piece of
code in a specific number of times.
• The following illustrates Perl for statement syntax:
for(initialization; test; increment){
statements;
}
For
Here is a code snippet to print a message 10 times.
for($counter = 1; $counter <= 10; $counter++){
print "for loop #$counter\n";
}
Perl allows you to omit the initialization and increment part
of for statement. You can initialize outside the loop and increase
control variable inside the block as follows:
$counter = 1
for(; $counter < 10;){
print "for loop #$counter\n";
$counter++;
}
While
• Perl While statement is a Perl control structure that
allows to execute a block of code repeatedly.
• The Perl while statement is used when you want to
check a boolean condition before making a loop.
• The following illustrates the Perl while statement syntax:
while(condition){
#statements;
}
While
$x = 0;
while($x < 5){
print "$x\n";
$x++;
}
Do While
• Beside while loop, Perl also provides do while loop
statement.
• do while loop statement is similar to while loop but it checks
the loop condition after executing the block therefore block
executes at least one time.
• Here is a code snippet to demonstrate do while statement:
$x = 0;
do{
print "$x\n";
$x++;
}while($x < 5);
ARRAYS
Lists
• Scalar variable allows you to store single element such as
number or string. When you want to manage a collection
or a list of scalar data you use list. Here are some
examples of lists.
("Perl","array","tutorial");
(5,7,9,10);
(5,7,9,"Perl","list");
(1..20);
();
Array Variables
• To store lists of values to use throughout your program
you need array variables.
• Array variable is used to hold a list of data.
• Different from scalar variables, array variables are
prefixed with the at sign(@). For example we have five
array variables to store five lists above as follows:
@str_array =
("Perl","array","tutorial");
@int_array = (5,7,9,10);
@mix_array = (5,7,9,"Perl","list");
@rg_array = (1..20);
@empty_array = ();
Operations on Arrays
Here is the code snippet to demonstrate each function above:
@int =(1,3,5,2);
push(@int,10); #add 10 to @int
print "@int\n";
$last = pop(@int); #remove 10 from @int
print "@int\n";
unshift(@int,0); #add 0 to @int
print "@int\n";
$start = shift(@int); # add 0 to @int
print "@int\n";
Operations on Arrays
You can add or remove elements to/from an array. Here is
a list of common operations on arrays:
• push(@array,$element) add $element to the end of array @array
• pop(@array) remove the last element of array @array and
returns it.
• unshift(@array,$element) add $element to the start of array
@array
• shift(@array) remove the first element from array @array and
returns it.
HASH
What is hash?
• When number of item in an array is bigger, the
performance is degraded also. Perl createdhash - before
that is it called associative array - to overcome this
limitation. Hash is another kind of collective data type.
Hash can hold as many as scalar like array but the way
you accessing hash element is different. You access hash
element in has by using a key.Each has element has two
parts: key and value or key-value pair.
Hash
• The key identifies the value of element associated with
it. To define a hash variable, you use percentage sign (%)
as follows:
• %websites = (
• "perltutorial.org" => "Perl tutorial",
• "Perl.org" => "Perl directory"
• );
Accesing Hash Elements
To access a hash element, you use the key of that element
to retrieve the value as follows:
print $websites{"perltutorial.org"}; #Pe
rl tutorial
Filling Hash Elements
You can define hash as above example or use a list as follows:
%websites = (
"perltutorial.org" => "Perl tutorial",
"Perl.org" => "Perl directory"
);
Another way to fill the hash element by using key-value pair and
assignment operator as follows:
$websites{"Perl.com"} = "Perl.com
homepage";
print $websites{"Perl.com"}; #Perl.com
homepage
Testing a Key
To test whether a key exists in a hash, you use exist function provided
by Perl. Here is the syntax:
if ( exists $hash{key} ){
#retrieve value here
}
For example, we can test whether key "perltutorial.org" exists
in %websites hash by using the above pattern:
%websites = (
"Perltutorial.org" ,"Perl tutorial",
"Perl.org", "Perl directory"
);
if(exists $websites{"Perltutorial.org"}){
#Perl tutorial
print $websites{"Perltutorial.org"};
}
Remove a Key from Hash
To remove a single key from hash, you use delete function
as follows:
delete $hash{key};
To remove all keys and values from a hash, you just assign
hash to an empty list:
%hash = ();
Looping through a hash
To loop through a hash you use foreach statement. First
you retrieve all keys of the hash by using keys function.
Based on this list you can find all elements of the hash.
Here is the syntax:
foreach $element (keys %hash){
#process hash element here
}
Looping through a hash
For example, we can loop through %websites hash:
%websites = (
"Perltutorial.org" ,"Perl tutorial",
"Perl.org", "Perl directory"
);
foreach $website (keys %websites){
print "$website is about
$websites{$website}\n";
}
#output:
#Perltutorial.org is about Perl tutorial
#Perl.org is about Perl directory
Array and Hash
• You can assign an hash to an array and vice versa. For
example:
• %websites = (
• "Perltutorial.org" =>"Perl tutorial",
• "Perl.org" => "Perl directory"
• );
• @websites = %websites;
SUBROUTINES
Define a Subroutine
To define subroutine you use the keyword sub followed by
subroutine name and its body. Here is the syntax of
subroutine definition.
sub subroutine_name{
#subroutine body
}
For example, here is a simple subroutine to print a
message.
sub print_message{
print "Perl subroutine tutorial";
}
Call a Subroutine
To invoke or call subroutine, you use the subroutine name
with the ampersand (&) prefixed as follows:
&print_message;
Parameters
Parameters are passed to a subroutine as a list which is
available in a subroutine as a @_ - an array variable. For
example:
sub print_list{
print "@_\n";
}
#print: this is Perl subroutine tutorial
&print_list("this","is","Perl","subroutine","tut
orial");
#print: subroutine tutorial
8&print_list("subroutine","tutorial");
Parameters
In the line 2, we printed the list variable which was the input parameters of the
subroutine. In line 5 and 7, we called subroutine with different list and we got
different output.
You can refer to each parameter in a list by using scalar $_[index] for example:
sub max{
if($_[0] > $_[1]){
$_[0];
}
else{
$_[1];
}
}
$m = max(10,20);
$m2 = max(50,30);
print "$m\n";
print "$m2\n";
Returning Values
Subroutine returns values which is the last expression
evaluated. For example :
sub cal_sum{
print "sum of two numbers\n";
$_[0] + $_[1];
}
$result = &cal_sum(10,20); # result is
30
print $result;
Returning Values
If you want to return value immediately from subroutine, you
can use returnoperator, for example:
sub min{
if($_[0] < $_[1]){
return $_[0];
}
else{
return $_[1];
}
}
$m = &min(10,20); # result is 10
print $m;
Returning a List of Values
Subroutine returns not only scalar value but also a list of
values. Let's take a look at an example below:
sub get_list{
return 5..10;
}
@list = &get_list;
print "@list"; #5 6 7 8 9 1
FIN
Download