An Introduction to Perl – Part I

Download Report

Transcript An Introduction to Perl – Part I

An Introduction to Perl
Part I
Jonathan Stanley
CS265
An Introduction to Perl
Part I
 Introduction
 Scalar Data
 Variables
 Operators
 If-Else Control Structures
 While Control Structures
 Standard Input
 Lists and Arrays
Introduction
What is Perl?
Scalar Data
Numbers
Strings
Perl has two types of numbers:
A string is a sequence of characters
Integers => 4 or 20
Floating point numbers => 2.3 or 4.5
In Perl, strings can have single or
double quotes.
Implementation => $var=4; or
Implementation => $var=3.5;
Implementation => $var=‘a’;
Implementation => $var=“new/nLine”;
Variables
In Perl, variables are declared with the $ symbol.
They may contain a combination of letters, numbers,
and underscores but cannot begin with a number.
Comments are also denoted as #.
$Num2=5; #Num2 has the value of 5
$my_name=‘Jon’; #my_name has the value “Jon”
Numerical Operators
Assignment Operators
=, +=, -=, *=, /=, %=, **=
$var=265;
$var-=265;
$var+=265;
Comparison Operators
==, !=, <, >, <=, >=
$var==1;
$var!=0;
Arithmetic Operators
+, -, *, /, %, **
$var=1+3;
$var=9–4;
$var=3*2;
$var=8/2;
$var=6%4;
$var=3**2;
String Operators
Assignment Operators
=, .=
$var=“yes”
$var.=“ or no”
Comparison Operators
eq, ne, lt, gt, le, ge
$var eq “yes”;
$var gt “apple”;
Logical Operators
&&, ||, !
($var==“yes”) && ($var2==2)
($var==“yes”) || ($var2==2)
($var==“yes”) != ($var2==2)
Contamination Operator
. (dot symbol)
“Jon”.“Stanley”
Multiplier Operator
x
“yes”x3
If-Else Control Structures
if ($class eq “CS265”)
{
print “What a good day :)” ;
}
else
{
print “What a bad day :(”;
}
While Control Structures
while($counter <= 3)
{
$counter++;
print $counter;
}
Standard Input
$var=<STDIN> ;
print “What is you name?";
chomp ($name = <>);
print “What is your major?";
chomp ($major= <>);
print “$name is currently studying $major at
Drexel University.";
Lists and Arrays
A list is an ordered collection of scalars while an array is a variable
that holds lists.
@list1=(“jon”, “jacob”, “jingleheimer”, “schmidt”);
@list2=(0..8);
print @list1[1]; #prints jacob
print @list2; #prints 0 1 2 … 8
push() - adds an element to the end of an array.
unshift() - adds an element to the beginning of an array.
pop() - removes the last element of an array.
shift() - removes the first element of an array.
@list1.shift();
@list1.unshift(); #After both, list1 contains 2 entries.
@list2.push(9); #adds 9 to the end
Questions?