47
 Perl Tutorial Pablo Manalastas <[email protected]LEARNING PERL

perl_lessons

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: perl_lessons

   

Perl TutorialPablo Manalastas <[email protected]

LEARNING PERL

Page 2: perl_lessons

   

Numbers

● Numbers are double precision floating point values (double in C)3,  1.5,  2.7e8,  2_427_132_115,0577, 0xf3ab, 0b1110001011

● Numeric operationsAdd (+), subtract (­), negate (­), multiply (*), divide (/), modulus (%)3 + 4.2,   2.3e4*6.2523,  10%4

Page 3: perl_lessons

   

Strings

● Can be any length & can contain any characters● Single­quoted strings'Pablo de Gracia, Jr.''The winter of our discontent.''Queen\'s Jewels'# the single quote ' is specified as \''The backslash \\ is special'# the backslash \ is specified as \\

Page 4: perl_lessons

   

Strings● Double­quoted strings”against earth's flowing breast”“I am called \”handsome\” by some”“I came.\nI saw.\nI conquered.\n”“Tab\tseparated\tentries\there”

● String concatenation“Hello ”  .  “world\n”

● String repetition“maganda ” x 3

Page 5: perl_lessons

   

Autoconversion: Numbers & Strings

● Arithmetic operations (+,­,*,/,%) convert strings to numbers“12plus2” + “3”   # gives the number 15

● String operation (.) converts numbers to strings“XJW” . 24*5  # gives the string “XJW120”

Page 6: perl_lessons

   

Variables

● Variable names[$@%][A­Za­z_][0­9A­Za­z_]*

● Scalar variables, name starts with $– Holds one value (scalar value)– Examples:$daily_rate = 350.00;$horse_name = “Heaven's Pride”;$monthly_pay = $daily_rate * 22;

Page 7: perl_lessons

   

Binary Assignment Operators

● Replace $var = $var op $val;by $var op= $val;

● Examples:$new_rate += 12;$quotient /= 10;$name .= “, PhD”;$balance ­= $withdrawal;

Page 8: perl_lessons

   

Output Using “print”

● Write output to stdout using print

print “Hello, world!\n”;print “The answer is ” . 350 * 6 . “\n”;print “The answer is ”, 350 * 6,“\n”;

Page 9: perl_lessons

   

Interpolation● Interpolation: the replacement of a scalar 

variable by its value in a double quoted string or when occuring alone

● Examples$meal = 'beef steak';print “Juan ate $meal\n”;print “I like $meal for dinner\n”;print “Juan's dinner is “ . $meal;print “Juan's dinner is “, $meal;

Page 10: perl_lessons

   

Delimiting the Variable Name

● Use { } to delimit the variable name to be interpolated

● Examples$what = 'steak';print “I love all kinds of ${what}s\n”;print “I love all kinds of $what”, “s\n”;print “Prime rib is the $what of ${what}s\n”;

Page 11: perl_lessons

   

Comparison Operators

● Numeric comparison operators==, !=, <, >, <=, >=Examples:50 == 100/2; # true100/3 != 33.3 # true

● String comparison operatorseq, ne, lt, gt, le, ge'pedro' lt 'jose' # false'jose' eq “jose” # true' ' gt ''# true

Page 12: perl_lessons

   

Boolean Values● undef, number zero (0), string zero ('0'), the 

empty string (''), are all false. Undef designates a variable with no value assigned yet.

● non­zero numbers (like 1) and non­empty strings (except '0') are all true. 

● Examples$bool1 = 'Fred' lt 'fred';$bool2 = 'fred' lt 'Fred';print $bool1;   # prints 1 for trueprint $bool2;   # empty string for false

Page 13: perl_lessons

   

If Control Structure

● Syntaxif( condition ) { true­part; } else { false­part; }

● Example$disc = $b*$b – 4.0*$a*$c;if( $disc >= 0.0 ) {  print “Real roots\n”;} else {  print “Complex roots\n”;}

Page 14: perl_lessons

   

Reading One Line from Stdin

● Use <STDIN> to read one line from standard input, usually the console keyboard

● Examples:print “Enter first name: “;$fname = <STDIN>;print “Enter last name: “;$lname = <STDIN>;chomp($fname);chomp($lname);print “Your name: $fname $lname\n”;

Page 15: perl_lessons

   

The chomp() Function

● chomp() removes a trailing newline '\n' from the string value of a variable

● Version2 of program:print “Enter first name: “;chomp($fname = <STDIN>);print “Enter last name: “;chomp($lname = <STDIN>);print “Your name: $fname $lname\n”;

Page 16: perl_lessons

   

While Control Structure● Syntax:

initialization;while ( condition ) {   statements;   reinitialization;}

● Example:$i = 1;while($i <= 10) {  print “Counting $i\n”;  ++$i;}

Page 17: perl_lessons

   

UNDEF

● If an undefined variable is used as a number, undef is like zero (0). If used as a string, undef is like the empty string ('')

● If $x is undefined, the following are allowed:$x += 2;$x .= 'bye';

● If $x has a value, then$x = undef;makes $x undefined

Page 18: perl_lessons

   

The defined() Function● The <STDIN> operation may return the value 

undef when there is no more input, such as at end­of­file

● The function defined() can test if <STDIN> read one line of input from standard input.

● Examplewhile(defined($line = <STDIN>)) {  print “You typed: $line”;}print “No more input\n”;

Page 19: perl_lessons

   

Exercises● Write a Perl program that reads lines of input 

from <STDIN>, and prints each line read. Stop when the line that is read is 'Done' (without the quotes).

● Write a Perl program that reads the values of three variables $num1, $oper, and $num2 from <STDIN>.  If the value of $oper is one of the strings 'plus', 'minus', 'times', or 'over', the program should carry out the indicated operation on $num1 and $num2.

Page 20: perl_lessons

   

Lists & Arrays 

● List: an ordered collection of scalar values. The index is the position of a scalar value in the list. The index runs from 0 to (n­1), where n is the size of the list. An array is a variable that contains a list, and starts with a @sign

● Example:@quals@friends

Page 21: perl_lessons

   

Initializing Arrays with Literal Values● An array may be initialized with values in 

parentheses ( ). Example: @propty = ('Pablo', 62, 'male', undef);

Here, the array is @propty, and the values in the list are:$propty[0] is 'Pablo'$propty[1] is 62$propty[2] is 'male'$propty[3] is undef  #civil status

Page 22: perl_lessons

   

Values May All Be Same Type● All list values may be the same type@friends = ('Pablo', 'Jose', 'Juan', 'Mario', 'David');

Here, the array is @friends, and the values in the list are:$friends[0] is 'Pablo'$friends[1] is 'Jose'$friends[2] is 'Juan'$friends[3] is 'Mario'$friends[4] is 'David'

Page 23: perl_lessons

   

Values of Array Indices● Any value, variable, or expression, whose value is 

integer or can be converted to integer can be used as index.

● Example:$ndx = 2.5;$friends[$ndx+1] is $friends[3]

● $#friends is the value of the last index of array @friends, which is 4.

● $friends[$#friends+10] = 'Carlos';adds element 'Carlos' at index 14, the 15th element. Values at index 5 to 13 will be undef.

Page 24: perl_lessons

   

Initializing Array with Literal Values

● @arr = ( );@arr = (5..10, 17, 21);@arr = ($a..$b);@arr = qw/  Pablo Jose Mario /;@arr = qw! Pablo Jose Mario !;@arr = qw( Pablo Jose Mario );@arr = qw{ Pablo Jose Mario };@arr = qw< Pablo Jose Mario >;

Page 25: perl_lessons

   

Interpolate Arrays/Values in Strings● If @arr is an array, then array @arr and list 

value $arr[k] will be interpolated (evaluated) when placed inside double quoted strings

● Example interpolating arrays@arr = (5..7);print “Four @arr eight\n”;# will print Four 5 6 7 eight

● Example interpolating list values@toy = ('toycar', 'toyrobot', 'toygun');print “I have a $toy[2] at home\n”;

Page 26: perl_lessons

   

pop( ) Function

● pop() removes the rightmost list value from an array

● Example:@stk = (5..9);$a = pop(@stk);# remove 9 leaving 5..8, $a = 9$b = pop @stk;# remove 8 leaving 5..7, $b = 8pop @stk;    # remove 7 leaving 5..6

Page 27: perl_lessons

   

push() Function

● push(): adds new rightmost values to the list of an array

● Example:@stk = (5..8);push(@stk, 0);  # now (5,6,7,8,0)push @stk, (1..3);# now (5,6,7,8,0,1,2,3)@stk2 = qw/ 10 11 12 /;push @stk, @stk2; # now (5,6,7,8,0,1,2,3,10,11,12)

Page 28: perl_lessons

   

shift() and unshift()

● shift() is like pushing new first values, unshift() is like popping the first value.  These operations are done on the leftmost end of the array.

● @stk = (5..9);shift(@stk, 4);   # now (4..9)shift @stk, (1..3); # now (1..9)$a = unshift @stk;# remove 1 leaving (2..9), $a = 1

Page 29: perl_lessons

   

foreach Control Structure

● Syntax: foreach $var (@arr) { body; }● Example: form the pural form of each fruit:@fruits = qw/mango banana durian/;foreach $fr (@fruits) {  $fr .= 's';}print “@fruits\n”;

Page 30: perl_lessons

   

Perl's Default Variable: $_

● If you omit $var in a foreach loop, you can refer to this variable using $_foreach (1..10) {  $sum += $_;}print “Total of 1..10 is $sum\n”;

● If you omit $var in a print statement, the value of $_ will be printed.$_ = “Today is Saturday\n”;print;

Page 31: perl_lessons

   

reverse() and sort()● reverse(@arr) reverses the order of values in 

the list@fruits = qw/mango papaya chico/;@revfr = reverse(@fruits);@fruits = reverse(@fruits);

● sort(@arr) sorts the values in the list in increasing lexicographic order, or string order, not numeric order@fruits = qw/mango papaya chico/;@sfruits = sort(@fruits);@rfruits = reverse sort @fruits;

Page 32: perl_lessons

   

Forcing scalar() Context

● If you want to use an array @arr in a scalar context (for example, get the number of elements in the list), use the function scalar()@fruits = qw/mango banana orange/;print “Favorite fruits: @fruits\n“;print “My favorite fruits are “, scalar(@fruits), “ in all\n”;

Page 33: perl_lessons

   

<STDIN> as List or Scalar

● $line = <STDIN>;reads one line from <STDIN>

● @lines = <STDIN>;reads the entire file <STDIN> until end­of­file and assigns each line as an element of the array @lines. If file is big, @lines may use up a huge amount of memory. The end­of­file of <STDIN> is indicated by typing Control­D in Unix.

Page 34: perl_lessons

   

Sorting Lines from <STDIN>

● chomp(@lines = <STDIN>);@lines = sort @lines;foreach $line (@lines) {   print “$line\n”;}print “**No more**”;

Page 35: perl_lessons

   

Exercises● Write a program that reads from <STDIN> a set 

of numeric values, one per line, and computes the mean and variance of these values. If N is the number of values, thenmean = (sum of all values) / N;variance =   (sum square(each value – mean)) / N;

● Write a program that reads lines from <STDIN>, sorts these lines in reverse alphabetical order, prints the lines, and prints the total number of lines.

Page 36: perl_lessons

   

Hashes● A hash is a list of key­value pairs. The variable 

name starts with %%age = (“Pablo”, 62, “Karen”, 23, “Paul”, 33);Here the key “Pablo” has value 62, the key “Karen” has value 23, and the key “Paul” has value 33.

● Accessing a hash by key$age{“Paul”}  gives 33$age{“Karen”} gives 23

Page 37: perl_lessons

   

Hashes: Big Arrow Notation

● %lname = (“Pablo”=>”Manalastas”,“Rojo”=>”Sanchez”,“Joy”=>”Fernando”);

● %month = (1=>”January”, 2=>”February”,3=>”March”, 4=>”April”, 5=>”May”);

● $lname{“Rojo”} gives “Sanchez”$month{4} gives “April”

Page 38: perl_lessons

   

Using a Hash

● %lname = (“Pablo”=>”Manalastas”,“Rojo”=>”Sanchez”,“Joy”=>”Fernando”);print “Enter first name: “;chomp($fname = <STDIN>);print “Last name of $fname is “,  $lname{$fname}, “\n”;

Page 39: perl_lessons

   

Keys & Values● %month = (1=>”January”, 2=>”February”,3=>”March”, 4=>”April”, 5=>”May”);

● @k = keys %month;# @k is the array of keys only

● @v = values %month;# @v is the array of values only

Page 40: perl_lessons

   

each() & exists()● %month = (1=>”January”, 2=>”February”,3=>”March”, 4=>”April”, 5=>”May”);

● To access each (key,value) pair: while(($key,$val) = each %month) {  print “$key => $val\n”;}

● To check if a value exists for a keyIf( exists $month{13}) {  print “That is $month{13}\n”;}

Page 41: perl_lessons

   

Hash Element Interpolation

● %month = (1=>”January”, 2=>”February”,3=>”March”, 4=>”April”, 5=>”May”);

● Can interpolate each elementprint “First month is $month{1}\n”;

● Not allowedprint “The months are: %month\n”;

Page 42: perl_lessons

   

Exercises

● Write a program that reads a series of words (with one word per line) until end­of­input, then prints a summary of how many times each word was seen.

● Write a program that prompts for month number (1­12), day number (1­31), and year (1900­2008), and display the inputs in the form“MonthName  day, year” (without the quotes).

Page 43: perl_lessons

   

Subroutines

● User­defined functions that allow the programmer to reuse the same code many times in his program

● Subroutine name starts with &, in general● Defining a subroutinesub subName {  subBody;}

Page 44: perl_lessons

   

Example Function

● Defining a function:

sub greet {  print “Hello!\n”;}

● Using the function:

&greet;

Page 45: perl_lessons

   

Passing Arguments● If the subroutine invocation is followed by a list within 

parenthesis, the list is assigned to special variable @_ within the function

● Example&greet(“Pablo”, “Jose”, “Maria”);

You can use the arguments as follows:sub greet {  for each $name in (@_) {    print “Hello $name!\n”:  }} 

Page 46: perl_lessons

   

Local Variables; Returning Values

● sub sum {  local($total);  $total = 0;  for each $num in (@_) {    $total += $num;  }  $total;}

Page 47: perl_lessons

   

Exercises

● Write a function that returns the product of its arguments

● Write a function that accepts two arguments n and d, returns a list of two numbers q and r, where q is the quotient of n and d, and r is their remainder

● Write a function that, given any number n as argument, prints the value of that number in words, as in a checkwriter.