Documentos de Académico
Documentos de Profesional
Documentos de Cultura
UNIT-8
Eduoncloud.com
Page 1
UNIT-8
Basic Syntax
Variables
You dont have to declare a variable before you
access it
You don't have to declare a variable's type
Eduoncloud.com
Page 2
UNIT-8
What are the benefits of perl? What are the basic datatypes in perl.
--10
What are the three categories of perl variables? Give example for each. --06
Benefits of perl
support for communications using sockets
support for object-oriented programming
powerful text pattern-matching capabilities
Portability: Perl code that doesn't use system specific
features can be run on any platform
Basic Data-types.
T hree categories of variables in Perl:
Eduoncloud.com
Page 3
UNIT-8
--06
Numeric Literals
All numeric values are represented internally as doubleprecision floating point values.
Literal numbers are integers or floating point values.
Integers are strings of digits
# integer
# negative integer
# floating point
Page 4
6.02E23
0xffff
0377
UNIT-8
# scientific notation
# hexadecimal
# octal
String Literals
Quoting Strings
1. Strings enclosed in single quotes :
Everything is interpreted literally
2. Double-quoted string
3. With ` (backtick)
Eduoncloud.com
Page 5
UNIT-8
Generic
Meaning
''
q{}
Literal
no
""
qq{}
Literal
yes
``
qx{}
Command
yes*
qw{}
Word list
//
m{}
Interpolates
no
Pattern match
yes*
qr{}
Pattern
yes*
s{}{}
Substitution
yes*
tr{}{}
Transliteration
no
y{}{}
Transliteration
no
<<EOF
here-doc
yes*
The names of scalar variable all begin with $ and then continue with
a letter, followed by letters, digits and/or underscores.
Page 6
UNIT-8
$age = 47;
$myString = "Jack is $age years old ";
Implicit Variables
$_
$0
$]
@_
@ARGV
Eduoncloud.com
Page 7
UNIT-8
Numeric Operators
Operator
Associativity
++, -Unary +, -
Nonassociative
*
Right to left
** (exponentiation)
Right to left
*, /, %
Left to right
Binary +, -
Left to right
Operator
x
=
Operation
string concatenation
string repetition
concatenation and assignment
Example
$first = "Freddy"
$first " Freeloader"
Result
"Freddy
Freeloader"
Eduoncloud.com
Result
"More! More! More! "
Page 8
UNIT-8
--10
String Functions
Name
Parameter(s)
chomp
A string
length
A string
Lc
A string
Uc
A string
Hex
A string
Join
Actions
Keyboard Input
All input and output in Perl is treated as file I/O.
Files have external names, but are know within the program by
their internal names (known as "filehandles").
Three predefined filehandles: STDIN, STDOUT and STDERR.
Eduoncloud.com
Page 9
UNIT-8
chomp($in_data = <STDIN>);
#does not read newline
Screen Output
The standard way of producing output is the print
operator/function (which requires parentheses).
takes one or more string literals separated by commas.
print "This is pretty easy\n", By..;
C's printf function and its formatting specifiers are also available.
-----------------------------Example sum.pl ----------------------------------------
sum.pl
Page 10
UNIT-8
Relational Operators
Numeric
Operands
Operation
String
Operand
s
Is equal to*
==
!=
Ne
Is less than*
<
Lt
Is greater than*
>
Gt
<=
Le
>=
Ge
<=>
Cmp
Compare:
* Produces +1 if true,
Eq
"" is false
{
Page 11
UNIT-8
Simple if:
if ($ > 10)
$b = $a * 2;
}
}
elsif ($snowrate < 2) {
print "Moderate snow\n";
}
else {
print "Heavy snow\n";
}
unless
unless has essentially the same syntax as if, except the statements in
the block are executed if the condition is false.
Eduoncloud.com
Page 12
UNIT-8
Example
}
is the same as:
Explain briefly the different Loop structures in PERL. Give examples. --10
$sum = 0;
$sum = 0;
$sum = 0;
$count = 1;
$count = 1;
$sum += $count;
$sum += $count;
Assignment:
Example:1
Write program to read N number of values, and then to compute and print
sum and average of N entered values.
Eduoncloud.com
Page 13
UNIT-8
Example:2
Write program to read all numbers till End_of_File from keyboard and
then to compute and print sum and average.
--06
$i > 5; $i++)
last;
Loops and Labels in Perl
Using a label allows the programmer to decide which one of several
nested loops will be exited:
BIGLOOP:
while () {
while () {
while (..) {
if () { last BIGLOOP}
}
}
}
Eduoncloud.com
Page 14
UNIT-8
List Literals
A list is an ordered sequence of scalar values.
A list literal is a parenthesized list of scalar values and is
@mylist = ( 1, 10, 17 )
Lists can store any combination of different types of
scalar values:
( $val + 1, "circles", 17 )
Arrays
Arrays are variables that can store lists and begin with @
Scalars and arrays are in different namespaces, so there is no
connection between $a and $a[0].
Eduoncloud.com
Page 15
UNIT-8
$a = 10 ;
@a = (50, 60, 70) ;
print
scalar = $a;
# display 10
array's length.
$len
@list
Page 16
UNIT-8
Array Lengths
Array lengths are dynamic:
@list = ("Monday", "Tuesday", "Wednesday");
$list[4] = "Friday";
If you write:
@list = (2, 4, 6);
list[27] = 8; # Elements are 4 , but length is 28.
The Last subscript in a list
$#list
$#list + 1
$#list = 99
foreach Statement
The foreach statement in Perl allows the programmer to process
every member of an array:
Eduoncloud.com
Page 17
UNIT-8
Next:
Next: 17
Next:
Next: 34
1. pop
or list.
- Scalar or list is added to the end of the array.
Eduoncloud.com
Page 18
UNIT-8
Page 19
UNIT-8
Example:
Input:
#
#
$index = 0;
($name = <>)
{
$arrNames[$index++] = uc($name);
Page 20
UNIT-8
Hashes
Page 21
UNIT-8
Initializing Hashes
using a list:
%kids_age= ( "John" => 38, "Genny" = 36,
Page 22
UNIT-8
Example
%arrAge;
Eduoncloud.com
Page 23
UNIT-8
Environmental Variables
#!C:\perl\bin\perl.exe
print "Content-type: text/html\n\n";
print "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> \n";
<title>
References
Eduoncloud.com
Page 24
UNIT-8
value in braces:
$ref_ages = { 'Curly' => 41,
'Larry' => 38,
'Moe' => 43 };
Dereferencing
address) and the value stored at that address. The latter is called
dereferencing.
All dereferencing in Perl is explicit. This can be done by placing a
extra $ in fron of the variable's name:
$$ref_names[3] = "Maxine";
This can also be done by using the -> operator:
$ref_names -> [3] = "Maxine";
Eduoncloud.com
Page 25
--7
Functions
A function definition includes the function header and a block
of code that specifies its actions.
sub message
{
print "Hello!\n";
}
Global Variables:
Variables that appear only in a function and that are implicitly
declared are global.
Local Variables:
You can force variables to be local by using the word my or
local in front of the variable:
local $count = 0;
my $age = 30;
my($count, $sum) = (0, 0);
When local and global variables conflict in name, we use the local
variable.
[Type text]
Page 26
Passing by value
a copy of the parameters values are given to the function.
(one-way communication)
If changes do not need to be shared with the main
program, passing by value is preferable.
Passing by reference
a copy of the values addresses are given to the function.
(two-way communication)
Passing by value
All Perl parameters are passed through a special variable
called @_ .
The actual parameters are copied into @_.
If an array is a parameter, it is also copied into @_ (and
should be at the end of the parameter list).
Hashes are flattened into arrays.
@_ is passed by value.
Examples
sub add
{
$result = $_[0] + $_[1];
print "The result was: $result\n";
}
To call the subroutine and get a result:
add(1,2);
sub add
{
($numbera, $numberb) = @_;
[Type text]
Page 27
The shift function returns (and removes) the first element of an array.
sub add
{
my $num1 = shift;
my $num2 = shift;
my $result = $num1 + $num2;
print "The result was: $result\n";
}
Returning value
sub myfunc
{
if (@_)
{
return $_[0]+$_[1];
}
else
{
return 0;
}
}
Passing by reference
References to variables can be used as actual parameters,
which provides a pass by reference mechanism.
sub squeeze
{
my $ref_LIST = $_[0];
my $value, @new;
foreach $value ( @$ref_list )
{
if ($value > 0) {
push(@new, $values);
}
[Type text]
Page 28
}
}
function call:
squeeze( \@mylist );
[Type text]
Page 29
An Example tst_median.pl
# program to test a function that computes the median of a given array
# Parameter: A reference to an array of numbers
# Return value: The median of the array, where median is the middle element
# of the sorted array, if the length is odd; if the length is even, the median
# is the average of the two middle elements of the sorted array.
sub median
{
my $ref_List = $_[0];
$len = $#$ref_List + 1; #>>Compute the length
my @list = sort { $a <=> $b } @$ref_List; #>>Sort the array
if( $len % 2 == 1) # length is odd return
{
$list[$len/2]; #return middle element as median
}
else # length is even
{
Page 30
Pattern Matching
Perl has following powerful pattern-matching features
}
Substitutions
Page 31
Example
g modifier: tells to make changes for all occurrence, not just first.
$str = "Roser, Is it Rose, rose or ROSE
$str =~ s/Rose/rose/g;
$str =~ tr/A-Z/a-z/;
# translate upper to lower case
$str =~ tr/\,\.//;
# remove all commas and periods
Page 32
word_table.pl
# word_table.pl
# Input: A file of text in which all words are separated by
#
( whitespace, comma, a semicolon, a question mark , an
#
exclamation point, a period or a colon) may follow whitespace.
#
The input file is specified on the command line.
# Output: A list of all unique words in the input file, in alphabetical order.
while (<>)
{
@line_words = split /[\.,;:!\?]\s*/;
Frequency \n\n";
foreach $word (sort keys %freq) #>>> Display the words and their frequencies
{
print " $word \t\t $freq{$word} \n";
}
Eduoncloud.com
Page 33
Remembering Matches
print "$2
#will display
$1, $3\n";
July 4, 1776
It can be very useful to match a pattern and save the portions of the
string before the match, matching the pattern and after the match.
These are $`(before), $& (matching) and $'(after).
An Example
Eduoncloud.com
Page 34
Explain file handling in perl. Explain how files can be opened for
input and output in perl. 07
Explain file handling in perl with examples. --10
Character(s)
<
Eduoncloud.com
Meaning
>
>>
+>
Page 36
using seek
Some applications seek to re-write data that has just been read.
This requires the use of the +> file use specification and then
moving back to the beginning of the data just read using seek.
Syntax
Eduoncloud.com
Page 37