7.1.intro_perl

55
Introduction to Perl Part I By: Cédric Notredame (Adapted from BT McInnes)

Upload: ramesh1255

Post on 22-Jul-2016

213 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 7.1.intro_perl

Introduction to Perl

Part I

By: Cédric Notredame(Adapted from BT McInnes)

Page 2: 7.1.intro_perl

2

What is Perl? Perl is a Portable Scripting Language

No compiling is needed. Runs on Windows, UNIX, LINUX and cygwin

Fast and easy text processing capability Fast and easy file handling capability Written by Larry Wall “Perl is the language for getting your job done.”

Too Slow For Number Crunching Ideal for Prototyping

Page 3: 7.1.intro_perl

3

How to Access Perl

To install at home Perl Comes by Default on Linux, Cygwin, MacOSX www.perl.com Has rpm's for Linux www.activestate.com Has binaries for Windows

Latest Version is 5.8 To check if Perl is working and the version number

% perl -v

Page 4: 7.1.intro_perl

4

Resources For Perl Books:

Learning Perl By Larry Wall Published by O'Reilly

Programming Perl By Larry Wall,Tom Christiansen and Jon Orwant Published by O'Reilly

Web Site http://safari.oreilly.com

Contains both Learning Perl and Programming Perl in ebook form

Page 5: 7.1.intro_perl

5

Web Sources for Perl Web

www.perl.com www.perldoc.com www.perl.org www.perlmonks.org

Page 6: 7.1.intro_perl

6

The Basic Hello World Program

which perl pico hello.pl Program:

#! /…path…/perl -wprint “Hello World!\n”;

Save this as “hello.pl” Give it executable permissions

chmod a+x hello.pl Run it as follows:

./hello.pl

Page 7: 7.1.intro_perl

7

“Hello World” Observations

“.pl” extension is optional but is commonly used The first line “#!/usr/local/bin/perl” tells UNIX where

to find Perl “-w” switches on warning : not required but a really

good idea

Page 8: 7.1.intro_perl

Variables and Their Content

Page 9: 7.1.intro_perl

9

Numerical Literals Numerical Literals

6 Integer 12.6 Floating Point 1e10 Scientific Notation 6.4E-33 Scientific Notation 4_348_348 Underscores instead of

commas for long numbers

Page 10: 7.1.intro_perl

10

String Literals String Literals

“There is more than one way to do it!” 'Just don't create a file called -rf.' “Beauty?\nWhat's that?\n” “” “Real programmers can write assembly in any

language.”

Quotes from Larry Wall

Page 11: 7.1.intro_perl

11

Types of Variables

Types of variables: Scalar variables : $a, $b, $c Array variables : @array Hash variables : %hash File handles : STDIN, STDOUT, STDERR

Variables do not need to be declared Variable type (int, char, ...) is decided at run time

$a = 5; # now an integer $a = “perl”; # now a string

Page 12: 7.1.intro_perl

12

Operators on Scalar Variables

Numeric and Logic Operators Typical : +, -, *, /, %, ++, --, +=, -=, *=, /=, ||, &&, ! ect

… Not typical: ** for exponentiation

String Operators Concatenation: “.” - similar to strcat

$first_name = “Larry”; $last_name = “Wall”;$full_name = $first_name . “ “ . $last_name;

Page 13: 7.1.intro_perl

13

Equality Operators for Strings Equality/ Inequality : eq and ne

$language = “Perl”;if ($language == “Perl”) ... # Wrong!if ($language eq “Perl”) ... #Correct

Use eq / ne rather than == / != for strings

Page 14: 7.1.intro_perl

14

Relational Operators for Strings

Greater than Numeric : > String : gt

Greater than or equal to Numeric : >= String : ge

Less than Numeric : < String : lt

Less than or equal to Numeric : <= String : le

Page 15: 7.1.intro_perl

15

String Functions Convert to upper case

$name = uc($name); Convert only the first char to upper case

$name = ucfirst($name);

Convert to lower case $name = lc($name);

Convert only the first char to lower case $name = lcfirst($name);

Page 16: 7.1.intro_perl

16

A String Example Program Convert to upper case

$name = uc($name); Convert only the first char to upper case

$name = ucfirst($name);

Convert to lower case $name = lc($name);

Convert only the first char to lower case $name = lcfirst($name);#!/usr/bin/perl$var1 = “larry”;$var2 = “moe”;$var3 = “shemp”;……Output: Larry, MOE, sHEMP

Page 17: 7.1.intro_perl

17

A String Example Program

#!/usr/local/bin/perl$var1 = “larry”;$var2 = “moe”;$var3 = “shemp”;

print ucfirst($var1); # Prints 'Larry'print uc($var2); # Prints 'MOE'print lcfirst(uc($var3)); # Prints 'sHEMP'

Page 18: 7.1.intro_perl

18

Variable Interpolation

Perl looks for variables inside strings and replaces them with their value

$stooge = “Larry”print “$stooge is one of the three stooges.\n”;

Produces the output:Larry is one of the three stooges.

This does not happen when you use single quotesprint '$stooge is one of the three stooges.\n’;

Produces the output:$stooge is one of the three stooges.\n

Page 19: 7.1.intro_perl

19

Character Interpolation

List of character escapes that are recognized when using double quoted strings \n newline \t tab \r carriage return

Common Example :

print “Hello\n”; # prints Hello and then a return

Page 20: 7.1.intro_perl

20

Numbers and Strings are Interchangeable

If a scalar variable looks like a number and Perl needs a number, it will use it as a number

$a = 4; # a numberprint $a + 18; # prints 22$b = “50”; # looks like a string, but ...print $b – 10; # will print 40!

Page 21: 7.1.intro_perl

Control Structures: Loops and Conditions

Page 22: 7.1.intro_perl

22

If ... else ... statements

if ( $weather eq “Rain” ) {

print “Umbrella!\n”; }

elsif ( $weather eq “Sun” ) { print “Sunglasses!\n”;}else { print “Anti Radiation Armor!\n”;}

Page 23: 7.1.intro_perl

23

Unless ... else Statements

Unless Statements are the opposite of if ... else statements.

unless ($weather eq “Rain”) { print “Dress as you wish!\n”;}else { print “Umbrella!\n”;}

And again remember the braces are required!

Page 24: 7.1.intro_perl

24

While Loop Example :

$i = 0;while ( $i <= 1000 )

{ print “$i\n”; $i++;}

Page 25: 7.1.intro_perl

25

Until Loop

The until function evaluates an expression repeatedly until a specific condition is met.

Example: $i = 0; until ($i == 1000) { print “$i\n”;

$i++;}

Page 26: 7.1.intro_perl

26

For Loops

Syntax 1: for ( $i = 0; $i <= 1000; $i=$i+2 )

{ print “$i\n”; }

Syntax 2: for $i(0..1000)

{ print “$i\n”; }

Page 27: 7.1.intro_perl

27

Moving around in a Loop

next: ignore the current iteration last: terminates the loop.

What is the output for the following code snippet:for ( $i = 0; $i < 10; $i++)

{ if ($i == 1 || $i == 3) { next; } elsif($i == 5) { last; }

else {print “$i\n”;} }

Page 28: 7.1.intro_perl

Answer

024

Page 29: 7.1.intro_perl

29

Exercise Use a loop structure and code a program that

produces the following output:

AAAAAAAAABAAABAAAABAAAAABAAAAAABAAAB

…..

TIP: $chain = $chain . “A”;

Page 30: 7.1.intro_perl

30

Exercise

#! /usr/bin/perl

for ($i=0, $j=0; $i<100; $i++){

if ( $j==3){$chain.=“B”;$j=0;}else {$chain.=“A”; $j++;}print “$chain\n”;

}

Page 31: 7.1.intro_perl

31

Exercise: Generating a Random Sample

A study yields an outcome between 0 and 100 for every patient. You want to generate an artificial random study for 100 patients:

Patient 1 99Patient 2 65Patient 3 89….

Tip:- use the srand to seed the random number generator

-use rand 100 to generate values between 0 and 100 :

rand 100

Page 32: 7.1.intro_perl

32

Exercise

for ($i=0; $i<100; $i++){$v=rand 100;#print “Patient $i $v\n”;printf “Patient %d %.2f\n\n”, $i, $v;#%s : chaines, strings#%d : integer#%f : floating points}

Page 33: 7.1.intro_perl

Collections Of Variables: Arrays

Page 34: 7.1.intro_perl

34

Arrays

Array variable is denoted by the @ symbol @array = ( “Larry”, “Curly”, “Moe” );

To access the whole array, use the whole array print @array; # prints : Larry Curly Moe

Notice that you do not need to loop through the whole array to print it – Perl does this for you

Page 35: 7.1.intro_perl

35

Arrays cont…

Array Indexes start at 0 !!!!!

To access one element of the array : use $ Why? Because every element in the array is scalar

print “$array[0]\n”; # prints : Larry

Question:

What happens if we access $array[3] ?

Answer1 : Value is set to 0 in Perl Answer2: Anything in C!!!!!

Page 36: 7.1.intro_perl

36

Arrays cont ...

To find the index of the last element in the arrayprint $#array; # prints 2 in the previous

# example

Note another way to find the number of elements in the array:$array_size = @array; $array_size now has 3 in the above example

because there are 3 elements in the array

Page 37: 7.1.intro_perl

37

Sorting Arrays Perl has a built in sort function Two ways to sort:

Default : sorts in a standard string comparisons order sort LIST

Usersub: create your own subroutine that returns an integer less than, equal to or greater than 0

Sort USERSUB LIST The <=> and cmp operators make creating sorting

subroutines very easy

Page 38: 7.1.intro_perl

38

Numerical Sorting Example

#!/usr/local/bin/perl -w@unsortedArray = (3, 10, 76, 23, 1, 54);@sortedArray = sort numeric @unsortedArray;

print “@unsortedArray\n”; # prints 3 10 76 23 1 54print “@sortedArray\n”; # prints 1 3 10 23 54 76

sub numeric {

return $a <=> $b;

}# Numbers: $a <=> $b : -1 if $a<$b , 0 if $a== $b, 1 if $a>$b # Strings: $a cpm $b : -1 if $a<$b , 0 if $a== $b, 1 if $a>$b

Page 39: 7.1.intro_perl

39

#!/usr/local/bin/perl -w@unsortedArray = (“Larry”, “Curly”, “moe”);@sortedArray = sort { lc($a) cmp lc($b)} @unsortedArray;

print “@unsortedArray\n”; # prints Larry Curly moeprint “@sortedArray\n”; # prints Curly Larry moe

String Sorting Example

Page 40: 7.1.intro_perl

40

Foreach

Foreach allows you to iterate over an array Example:

foreach $element (@array) { print “$element\n”;}

This is similar to : for ($i = 0; $i <= $#array; $i++) { print “$array[$i]\n”;}

Page 41: 7.1.intro_perl

41

Sorting with Foreach

The sort function sorts the array and returns the list in sorted order.

Example : @array( “Larry”, “Curly”, “Moe”); foreach $element (sort @array)

{ print “$element ”; }

Prints the elements in sorted order: Curly Larry Moe

Page 42: 7.1.intro_perl

42

Exercise: Sorting According to Multiple Criterion

Use the following initialization to sort individuals by age and then by income:

Syntax

@sortedArray = sort numeric @unsortedArray;sub numeric

{ return $a <=> $b;

}Data

@index=(0,1,2,3,4);@name=(“V”,“W”,”X”,”Y”,”Z”);@age=(10,20, 15, 20, 10);@income=(100,670, 280,800,400);

Output: Name X Age A Income I

Tip:-Sort the index, using information contained in the other arrays.

Page 43: 7.1.intro_perl

43

Exercise: Sorting According to Multiple Criterion

@index=(0,1,2,3,4,5);@name=(“V”,“W”,”X”,”Y”,”Z”);@age=(10,20, 15, 20, 10);@income=(100,670, 280,800,400);

foreach $i ( sort my_numeric @index){

print “$name[$i] $age[$i] $income[$i];}

sub my_numeric {

if ($age[$a] == $age[$b]){return $income[$a]<=>$income[$b]; }

else {return $age[$a]<=>$age[$b]; }

}

Page 44: 7.1.intro_perl

Manipulating Arrays

Page 45: 7.1.intro_perl

45

Strings to Arrays : split

Split a string into words and put into an array@array = split( /;/, “Larry;Curly;Moe” );@array= (“Larry”, “Curly”, “Moe”);

# creates the same array as we saw previously

Split into characters@stooge = split( //, “curly” );# array @stooge has 5 elements: c, u, r, l, y

Page 46: 7.1.intro_perl

46

Split cont.. Split on any character

@array = split( /:/, “10:20:30:40”);# array has 4 elements : 10, 20, 30, 40

Split on Multiple White Space@array = split(/\s+/, “this is a test”;# array has 4 elements : this, is, a, test

More on ‘\s+’ later

Page 47: 7.1.intro_perl

47

Arrays to Strings

Array to space separated string@array = (“Larry”, “Curly”, “Moe”);$string = join( “;“, @array);

# string = “Larry;Curly;Moe”

Array of characters to string@stooge = (“c”, “u”, “r”, “l”, “y”);$string = join( “”, @stooge );

# string = “curly”

Page 48: 7.1.intro_perl

48

Joining Arrays cont… Join with any character you want

@array = ( “10”, “20”, “30”, “40” );$string = join( “:”, @array);

# string = “10:20:30:40”

Join with multiple characters@array = “10”, “20”, “30”, “40”);$string = join(“->”, @array);

# string = “10->20->30->40”

Page 49: 7.1.intro_perl

49

Arrays as Stacks and Lists

To append to the end of an array :@array = ( “Larry”, “Curly”, “Moe” );push (@array, “Shemp” );print $array[3]; # prints “Shemp”

To remove the last element of the array (LIFO)$elment = pop @array;print $element; # prints “Shemp” @array now has the original elements (“Larry”, “Curly”, “Moe”)

Page 50: 7.1.intro_perl

50

Arrays as Stacks and Lists

To prepend to the beginning of an array@array = ( “Larry”, “Curly”, “Moe” );unshift @array, “Shemp”;print $array[3]; # prints “Moe”print “$array[0]; # prints “Shemp”

To remove the first element of the array $element = shift @array;print $element; # prints “Shemp” The array now contains only :

“Larry”, “Curly”, “Moe”

Page 51: 7.1.intro_perl

51

Exercise: Spliting Instructions

Remove shift: beginning, pop: end

Add Unshift: beginning, push: end

Use split, shift and push to turn the following string:

“The enquiry 1 was administered to five couples”“The enquiry 2 was administered to six couples”“The enquiry 3 was administered to eigh couples”

Into“five couples were administered the enquiry 1”

….

Page 52: 7.1.intro_perl

52

Exercise: Spliting Use split, shift and push to turn the following string:

$s[0]= “The enquiry 1 was administered to five couples”;$s[1]= “The enquiry 2 was administered to six couples”;$s[2]= “The enquiry 3 was administered to eigh couples”;foreach $s(@s)

{@s2=split (/was administered to/, $s);$new_s=“$s2[1] were admimistered $s2[0]”;print “$new_s\n”;

}

Page 53: 7.1.intro_perl

Multidimentional Arrays

Page 54: 7.1.intro_perl

54

Multi Dimensional Arrays

Better use Hash tables (cf later) If you need to:

@tab=([‘Monday’,’Tuesday’],[‘Morning’,’Afternoon’,’Evening’]);

$a=$tab[0][0] # $a == ‘Monday’$tab2=(‘midnight’,  ‘Twelve’);$tab[2]=\@tab2 # integrate tab2 as the last row

of tab

Page 55: 7.1.intro_perl

Thank you