perl training cvs

98
Perl Training Chaitanya CVS

Upload: nahush-bhat

Post on 12-Mar-2015

29 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Perl Training Cvs

Perl TrainingChaitanya CVS

Page 2: Perl Training Cvs

Getting Started

Perl is an acronym, short for Practical Extraction and Report Language. Parse tool reports OR build your own tools

Page 3: Perl Training Cvs

First code ☺

A Sample Perl Program –Create a file called program1_1.pl

#!/usr/intel/bin/perl $inputline = <STDIN>; print( $inputline );

Running a Perl ProgramTo run the program shown, do the following:

Make the file executable. chmod +x program1_1

Page 4: Perl Training Cvs

First code debug

Now create another file program1_2 and copy the following:#!/usr/intel/bin/perl

$inputline = “Hello world\n”print “$inputline”

Run the script. What do you see?Debug ☺

Page 5: Perl Training Cvs

Exercise 1:

Program1_1:#!/usr/intel/bin/perl $inputline = <STDIN>; print( $inputline );

Modify program1_1 to read two input lines and print only the second one.Modify program1_1 to read and print two different input lines. Modify program1_1 to print the input line twice.

Page 6: Perl Training Cvs

Basic Operators and Control Flow

Page 7: Perl Training Cvs

Basic Operators

Storing in Scalar Variables Assignment The Definition of a Scalar Variable Scalar Variable Syntax Assigning a Value to a Scalar Variable

Performing Arithmetic Example of Miles-to-Kilometers Conversion

Expressions Assignments and Expressions

Other Perl Operators

Page 8: Perl Training Cvs

Definition of Scalar VariablesLegal scalar variable names:

$x $var $my_variable $var2 $a_new_variable

Illegal scalar variable names: variable # the $ character is missing$ # there must be at least one letter in the name$47x # second character must be a letter$_var # again, the second character must be a letter$variable! # you can't have a ! in a variable name

Perl variables are case-sensitive. This means that the following variables are different: $VAR, $var, $Var

Page 9: Perl Training Cvs

Assigning Basic operators

$name = "John Q Hacker"; $var = 42; Some operations:$var = 17 + 5 - 3; You can use the value of a variable in an arithmetic operation, as follows: $var1 = 11; $var2 = $var1 * 6; Now examine the following statements: $var = 11; $var = $var * 6;

Question: What will $var store?

Page 10: Perl Training Cvs

Exercise 2.1:

#!/usr/intel/bin/perlprint ("Enter the distance to be converted:\n"); $originaldist = <STDIN>; chomp ($originaldist); $miles = $originaldist * 0.6214; $kilometers = $originaldist * 1.609; print ($originaldist, " kilometers = ", $miles, " miles\n"); print ($originaldist, " miles = ", $kilometers, " kilometers\n");

Does it work?

Page 11: Perl Training Cvs

Exercises 2.2:

• Use exercise 2.1 as a model and build a Rupee -> US Dollar converter. Use 40.50 rupees as the conversion factor for 1 dollar

• Write a program that reads two integers from standard input (one at a time), divides the first one by the second one, and prints out the quotient (the result) and the remainder.

Page 12: Perl Training Cvs

Control flow - If loop

Program containing a simple example of an if statement.

#!/usr/intel/bin/perlprint ("Enter a number:\n"); $number = <STDIN>; chomp ($number); if ($number == 0) { print ("The number is zero.\n");

}

print ("This is the last line of the program.\n");

Does it work?

Page 13: Perl Training Cvs

Control flow - IF loop with comparison#!/usr/intel/bin/perlprint ("Enter a number:\n"); $number1 = <STDIN>; chomp ($number1); print ("Enter another number:\n");$number2 = <STDIN>; chomp ($number2); if ($number1 == $number2) { print ("The two numbers are equal.\n");

} print ("This is the last line of the program.\n");

Page 14: Perl Training Cvs

If – Elsif - Else loop with comparison#!/usr/intel/bin/perlprint ("Enter a number:\n"); $number1 = <STDIN>; chomp ($number1); print ("Enter another number:\n"); $number2 = <STDIN>; chomp ($number2); if ($number1 == $number2) { print ("The two numbers are equal.\n");

} elsif ($number1 == $number2 + 1) { print ("The first number is greater by one.\n");

} else { print ("The numbers are not equal.\n");

} print ("This is the last line of the program.\n");

Page 15: Perl Training Cvs

Control flow - While loopCreate the following code:

#!/usr/intel/bin/perl$done = 0; $count = 1; print ("This line is printed before the loop starts.\n"); while ($done == 0) { print ("The value of count is ", $count, "\n"); if ($count == 3) { $done = 1;

} $count = $count + 1;

} print ("End of loop.\n");

Note: You can nest if inside while and while inside if (multiple if and while loops are allowed)

Page 16: Perl Training Cvs

Control flow - Until loop

A program that uses the until statement.#!/usr/intel/bin/perl

print ("What is 17 plus 26?\n"); $correct_answer = 43; $input_answer = <STDIN>; chomp ($input_answer); until ($input_answer == $correct_answer) { print ("Wrong! Keep trying!\n"); $input_answer = <STDIN>; chomp ($input_answer);

} print ("You've got it!\n");

Page 17: Perl Training Cvs

More operators

Operator Description< Less than> Greater<= Less than or equal to>= Greater than or equal to== Equal!= Not equal to<=> Comparison returning 1,

0, or -1

Page 18: Perl Training Cvs

Exercises 3 (10 mins)

1. Write a Perl program that reads in a number, multiplies it by 2, and prints the result.

2. Write a Perl program that reads in two numbers and does the following:

It prints Error: can't divide by zero if the second number is 0. If the first number is 0 or the second number is 1, it just prints the first number (because no division is necessary). In all other cases, it divides the first number by the second number and prints the result.

Page 19: Perl Training Cvs

Arrays

Page 20: Perl Training Cvs

Variables: @ArraysAn array holds a list of scalar elements Arrays are preceded by the “@” sign.Creating An Array$three = 3;@array1 = (1, 2, $three); # Set equal to 2 integers & 1 scalar.@array2 = @array1; # Copy @array1 contents to @array2.

Printing an arrayprint “@array1”; => 1 2 3Accessing Individual Array Elements

$first_element = $array[0];$second_element = $array[1];

Using a -1 subscript is a fast way to get the value of the last element in an array.Length of array $length = @array;

Page 21: Perl Training Cvs

Time to try out arrays

Code the following problem and execute:

#!/usr/local/bin/perl@array = (1, "chicken", 1.23, "\"Having fun?\"", 9.33e+23); $count = 1; while ($count <= 5) { print ("element $count is $array[$count-1]\n"); $count++;

} $length = @array;print (“The length of array is $length\n”);

Page 22: Perl Training Cvs

Variables: @ArraysAdding & Removing Elements From An Array, Part II

The push function accepts a list of values to be inserted at the end of an array.The pop function removes a value from the end of an array.The pop function returns undef if given an empty array.Examples

@list = (1,2,3);print @list;push(@list,4,5,6); # Add ‘4’, ‘5’, & ‘6’ to end of the array.print @list; => 123456$lastvalue = pop(@list); # Remove the last element & store in $lastvalue.print $lastvalue; => 6print @list; => 12345

Page 23: Perl Training Cvs

Variables: @ArraysAdding & Removing Elements From An Array, Part III

The shift & unshift functions do the same things to the left side of the array as push & pop do to the right side of the array.unshift inserts elements to the beginning of an array.shift deletes elements from the beginning of an array.Examples

@list = (1,2,3);print @list; => 123unshift(@list,4,5,6); # Add ‘4’, ‘5’, & ‘6’ to the beginning of the array.print @list; => 456123$firstvalue = shift(@list); # Remove the first element & store in $firstvalue.print $firstvalue; => 4print @list; => 56123

Note: The push and pop functions are more efficient with large arrays.

Page 24: Perl Training Cvs

Variables: @ArraysJust to refreash …

pop(@array) remove element from right hand sidepush(@array, $vars…)add element[s] to right

hand sideshift(@array) remove element from

left hand sideunshift(@array, $vars…) add element[s] to

left hand side

Page 25: Perl Training Cvs

Variables: @ArraysMerging Two Arrays @array(1, 2, 3); @array2 = (@array, @array); print @array2; => 123123

Reversing An ArrayUse the reverse function to reverse the order of an array.@array = (1, 2, 3); @array2 = reverse(@array);print @array2; => 321

Page 26: Perl Training Cvs

Variables: @ArraysSorting An Array

The sort function sorts in ascending ASCII order.A chart listing the full ASCII character order is located in the backups section of this presentation.

Examples@sizes = (“small”,”medium”,”large”); @array = sort(@sizes); # Sort array of strings.print “@array”; => large medium small

@array2 = (1,2,4,8,16,32,64); @array3 = sort(@array2); # Sort array of integers.print “@array3”; => 1 16 2 32 4 64 8

Page 27: Perl Training Cvs

Variables: @ArraysSplitting A String Into An Array

Use the split function to make an array out of a scalar string.$line = "moe::11:10:Mike:/home:/usr"; @fields = split(/:/, $line); # Split at colon’s, ‘:’. Store in @fields.

@fields now contains: ("moe","","11","10",“Mike", “/home”,”/usr”)$line = “here”;@chars = split(//, $line); # Split each character of $line.

@chars now contains: (“h",“e",“r",“e")Joining An Array Into A String

Use the join function to make a scalar string out of an array.$outline = join(":", @fields); # Join each element of an array with “:”.print $outline; => moe::11:10:Mike:/home:/usr

Page 28: Perl Training Cvs

Control flow for arraysThe foreach Control Structure

The foreach structure is used to iterate over a list of values, one by one.Unlike the for structure, there is no separate counter control variable to manage the repetition structure.Example

@array = qw(one, two, three);foreach $element (@array) {

print “$element “;}=> one two three

In this example, ‘$element’ represents one item of the list during each iteration of the loop. So during the first iteration, it is equal to “one”, the second iteration “two” and the final iteration “three”.

Page 29: Perl Training Cvs

Exercise 41. Given the following array:• @nums = (3, 2, 123, 34, 10, 1, 21, 134, 45, 0);

Write a script to find the largest value of the array.

2. Assign the line “ This perl training makes me sweat” to a variable. Split the line based on spaces and count the number of words in the lines.

Page 30: Perl Training Cvs

Hashes

Page 31: Perl Training Cvs

Variables: %Hashes“Remember everything in Perl is a list “Introduction To Hashes

A hash is an unordered collection of key-value pairs.A hash is similar to an array; however, hash elements are accessed with a string know as a key - not with a subscript value.Each key name must be unique.Accessing a non-existent hash key returns scalar zero.Hash variables are preceded by the percent symbol, “%”.Hashes require more memory than an array; however, they are useful when fast retrieval of values is required & are easier to use when handling chucks of key/value pairs.

Creating A Hash, %hash = (key => ‘value’ ); # Using the % sign$hash2{‘key’} = ‘value’; # Using a scalar assignment.

Page 32: Perl Training Cvs

Time to code in a hashes #!/usr/intel/bin/perl # Create a hash mapping layout layer names to their layer

numbers. %layerNums = (ndiff => 1, poly => 2, contact => 3, metal1 => 4); print %layerNums, “\n”; # => metal14contact3poly2ndiff1 $layerNums{‘metal2’} = 14; # Add a ‘metal2’ key-value pair to the

hash. print %layerNums, “\n”; # =>

metal14contact3poly2metal214ndiff1 delete($layerNums{‘poly’}); # Remove the ‘poly’ key-value pair. print %layerNums, “\n”; # => metal14contact3metal214ndiff1

Are you able to print?

Page 33: Perl Training Cvs

Hash FunctionsThe exists function checks if a hash element exists.

%layerNums = (ndiff => 1, poly => 2, contact => 3); if (exists($layerNums{‘poly’})) {

print “Element exists.”; => Element exists.} else {

print “Element doesn’t exist.”;}

The each function returns one key-value pair of a hash as a list in which the first element is the key and the second element is the value.

The each function is normally used in a loop to cycle through all the key-value pairs of a hash.

%layerNums = (ndiff => 1, poly => 2, contact => 3); ($key, $value) = each (%layerNums); # grab one key-

value p airprint "key: $key, value: $value\n“; => key:ndiff, value: 1

Page 34: Perl Training Cvs

Looping Over HashesThe following two examples illustrate how to loop over a hash with a foreach loop:foreach $key (keys %hash) {

print “$key -> $hash{$key}\n"; }

foreach $value (values %hash) { print “$value\n"; # print the values }

Page 35: Perl Training Cvs

Example Script#!/usr/intel/bin/perl# This script loops through the key-value pairs of a hash &

prints them out.%layerNums = (ndiff => 1, poly => 2, contact => 3, metal1 =>

4); while(($key, $value) = each(%layerNums)) {print “Layer: $key,\tLayer Number: $value\n”;

}Layer: metal1, Layer Number: 4Layer: contact, Layer Number: 3Layer: poly, Layer Number: 2Layer: ndiff, Layer Number: 1

Page 36: Perl Training Cvs

Coding again #!/usr/intel/bin/perl # More hash looping examples. %layerNums = (ndiff => 1, poly => 2, contact => 3); foreach (keys %layerNums) { print "\%layerNums contains $_ layer info.\n"; } foreach (values %layerNums) { print "\%layerNums contains the layer number: $_.\n"; }

Can you sort the keys and print?

Page 37: Perl Training Cvs

Sorting HashesSorting Hashes

The following examples illustrate an ascii sort on a hash’s keys & values.$hash{‘fruit’} = “apple”;$hash{‘sandwich’} = “hamburger”;$hash{‘drink’} = “coke”;foreach $key (sort keys %hash) {

print “$key => $hash{$key}\n”;}

drink => cokefruit => applesandwich => hamburger

foreach $value (sort values %hash) {print “$value”;

}prints apple coke hamburger

Page 38: Perl Training Cvs

The %ENV VariableThe %ENV variable is a special built-in hash that holds the current environmental variables.Environmental variables hold information about a shell’s environment.Examples

print $ENV{HOST}; # prints host nameforeach (keys %ENV) { # print all environmental

variablesprint “$_ => $ENV{$_}\n”;

}Changing the value of an environmental variable from within a Perl script will change that variable’s value for the duration of the script.

Page 39: Perl Training Cvs

Exercises

• 1. Write a script that given the following hash, prints out the number of existing key-value pairs:%greekAlphabet = (alpha => ‘a’, beta => ‘b’, gamma => ‘g’, delta => ‘d’);

• 2. Define the following array. • @cellNames = (“n4t”, “p4t”, “ntg4t”, “p4t”, “bufferA”, “bufferA”,

“bandgap”,“ntg4t”, “vdnmos”, “driver”, “predriver”, “ntg4t”);

Write code, using a hash, that determines if there are any duplicate values in the array. Output the cell name of those cells that are duplicated.

Page 40: Perl Training Cvs

File Processing

Page 41: Perl Training Cvs

Agenda

File ProcessingCommand Line ArgumentsFile Input/OutputThe Diamond OperatorFile Test OperatorsExercises

Page 42: Perl Training Cvs

Opening A File• The open function allows a file to be opened for read, write and/or

append access.

open (FILEHANDLE, “<file.txt”) or die “Could not open file: $!”;< # open for read access

> # create for write access

>> # open for append

+< # open for read & write

+> # create for read & write

• Closing a file:close(FILEHANDLE) or die “Cannot close file: $!”;

Page 43: Perl Training Cvs

Reading From A FileTo read a line from a file, use the specified FILEHANDLE surrounded by the diamond operator, ‘<>’.

Example$line = <FILEHANDLE>; # Read one line from FILEHANDLE

When the contents of a file are exhausted, <FILEHANDLE> will return false.

Page 44: Perl Training Cvs

Code: Reading From A File#!/usr/intel/bin/perl# Open .alias file & print out contents.

open (ALIAS, “.alias”) or die “Could not open file : $!”;# open .alias file in read mode

while(<ALIAS>) { # grab one line at a time

print; # print line}close(ALIAS) or die “Could not close file: $!”;#close .alias file

Page 45: Perl Training Cvs

Writing To A FileTo open a file for editing, use the open function and specify opening the file in write or append mode by using ‘>’ or ‘>>’.

To print data to a file, use the print function with two arguments:

The first argument is the FILEHANDLE.

The second argument is the string to be written to the file.

Example

#!/usr/intel/bin/perl

open (FH, “>file.txt”) or die “Could not open file : $!”;# open for edit

@array = (1, 2, 3);

print FH “Hello”; # print “Hello” to file

print FH @array; # print contents of @array to file

close (FH) or die “Cannot close file: $!”; # close file

Page 46: Perl Training Cvs

The @ARGV VariableThe @ARGV variable stores all command-line arguments.

The first command-line argument is stored in the $ARGV[0] variable, the second in $ARGV[1], etc…The name of the script is stored in the $0 variable.To loop over all command line arguments:

foreach $arg (@ARGV) {print “$arg\n”; # print command line args

}

Page 47: Perl Training Cvs

The @ARGV Variable#!/usr/intel/bin/perl

# loop through command line arguments & print linesforeach $arg (@ARGV) {

open(FH, “$arg”) or die “Could not open $arg: $!\n”;while(<FH>) {

print “$arg: $_\n”;}close(FH) or die “Could not close $arg: $!\n”;

}

Page 48: Perl Training Cvs

File Test OperatorsPerl provides several file test operators that allow a script to get information about a file.There are file test operators to check if files are readable, writable, executable, if the exist, etc…For example, the ‘-e’ operator tests whether or not a file exists.if(-e $filename && -w $filename) {

print “$filename exists\n”;} else {

print “$filename does not exist.\n”;}

Page 49: Perl Training Cvs

File Test OperatorsOperator Check

-A time since file last accessed in days

-B file a binary file

-d file is a directory

-e file exists

-f file is a plain file

-l file is a symbolic link

-M time since file last modified

-r file readable

-T file a text file

-w file writable

-x file executable

-z file has zero size

Page 50: Perl Training Cvs

Example Script #! /usr/intel/bin/perl

# This program prints the size of a file in bytes.

print “Enter the name of the file:\n”;

chomp ($filename = <STDIN>); # grab file name

if (!(-e $filename)) { # check if file exists

print “File $filename does not exist.\n”;

} else { # file exist’s

$size = -s $filename; # obtain file size

print “File $filename contains $size bytes.\n”;

}

Page 51: Perl Training Cvs

Exercises

1. Write a script that takes numeric values from the command line, adds them together, and prints the result.

2. Write a script that reads in a list of filenames from the command line and then displays which of the files are readable, writeable, executable and which ones don’t exist.

3. Write a script that copies the contents of one file into another new file (basically performing a copy operation). Make sure that the new file does not already exist.

Page 52: Perl Training Cvs

Executing shell commands

Page 53: Perl Training Cvs

Agenda

The System CommandBackticksPipes

Page 54: Perl Training Cvs

The system CommandThe system command is similar to exec in that it can be used to

execute shell commands; however, the system command returns back to the original process.

It does this by using a fork to create a separate child process which executes the shell command.

The original process (i.e. the perl script) waits until that forked child process finishes before continuing execution.

Examples

system(“clear”); # perform Unix’s clear command

system(“ls > dir.txt”); # perform ls command & direct output to a file

system(“mkdir scripts”); # make a scripts directory in cwd

Page 55: Perl Training Cvs

BackticksAs seen in the ‘String Manipulation’ slides, backticks can also be used to execute an external command.

The difference between backticks and the system command is that backticks will return the output of the forked process.

Examples:

@result = `dir –altr`; # perform dir & store output in @result

$wordcount = `wc $file`;# perform word count command & store result

A shorthand way to use backticks is with the qx() operator.

@result = qx(dir –altr);

Page 56: Perl Training Cvs

PipingAnother way to invoke an external command is to use a filehandle.

Writing to the filehandle will write to the standard input of the command.

Reading from the filehandle will read the command’s output.

This is the same concept as opening a filehandle for a file, except that:

An external command name is used in place of the file name.

A pipe, |, is appended to the command name.

Example Usage

open(FILEHANDLE, “command |”); # read output of an external command

open(FILEHANDLE, “| command”); # write to an external command

Env Example

open(ENV_FH, “env |”) or die “Could not open pipe: $!\n”;

print $_ while(<ENV_FH>); # print env variables

close(ENV_FH) or die “Could not close pipe: $!\n”;

Page 57: Perl Training Cvs

PipingDate Example

open(DATE_FH, “date |”) or die “Could not open pipe: $!\n”;$date = <DATE_FH>; # grab dateclose(DATE_FH) or die “Could not close pipe: $!\n”;

Sendmail (email) Example (works on HP & Linux)open(MAIL, “| mail [email protected]”) or die “Could not open $!”;print MAIL “Subject: This is the subject line\n\n”;print MAIL “This is the body.\n”;close(MAIL) or die “Could not close pipe: $!\n”;

Page 58: Perl Training Cvs

PipingUsing the tee command to open multiple files at once which correspond to a single filehandle:

open(FH, "|tee temp1 temp2 temp3") or die “FH: $!\n";print FH "hello\n";close(FH);

Page 59: Perl Training Cvs

Pattern Matching

Page 60: Perl Training Cvs

AgendaRegular Expressions Intro

RE Operators

Pattern Matching

RE Modifiers

Escape Characters

Quantifiers & Assertions

Grouping

Character Classes

Backreferencing

Pattern Substitution

Quantifier Greediness

Pattern Translation

Exercises

Page 61: Perl Training Cvs

Regular Expressions IntroA regular expression (RE) is a pattern of characters used to look for the same pattern of characters in another string.

Regular expressions are powerful tools when searching through text files and databases.

Page 62: Perl Training Cvs

Coding time #!/usr/intel/bin/perl

print “Ask me a question politely: \n”;$question = <STDIN>;if ($question =~ /please/i) { # search for “please”print “Thank you for being polite.\n”;

} else {print “That was not polite.\n”;

}

Page 63: Perl Training Cvs

Escape CharactersPerl provides several special escape characters for use in regular expressions.

\d match a digit character (0-9) \D match a non-digit character \s match a white-space character \S match a nonwhite-space character \w match a word character (a-z & A-Z) and “_” \W match a non-word character

All of Perl’s default escape characters (\a, \e, \E, \f, \l, \L, \n, \r, \t, \u, \U, etc…) behave exactly the same as in double-quoted string interpolation.

Page 64: Perl Training Cvs

Escape CharactersRegular Expression Escape Character Examples

$str = “There it is.”; if ($str =~ /\w\w\w/) { # matches ‘T’, ‘h’, ‘e’

print “There are three word characters”; } if ($str =~ /(\S\)s(\S)/) {

print “nonwhitespace_space_nonwhitespace”; print “$1 - $2\n”;

} if ($str !~ /\d/) {

print “There are no digits.”; } if ($str =~ /\D/) {

print “There are no digits.”; }

Page 65: Perl Training Cvs

Quantifiers & AssertionsPerl provides several special symbols called quantifiers that tell Perl to match multiple occurrences of a pattern at a time. . match any character except newline ? match zero or one times * match zero or more times + match one or more times {n} match n times {n,} match at least n times {n,m} match between n & m times (inclusive)

Perl also provides several special assertion characters which are used to anchor parts of a pattern. ^ match the beginning of the line $ match the end of the line (before newline) \b match a word boundary \B match a non-word boundary (matches only if pattern

contained in a word)

Page 66: Perl Training Cvs

Pattern MatchingMatch The Beginning Of A Line $line = “.Hello there!”; if ($line =~ m/^\./) {

print “Don’t start with a period”; }Match The End Of A Line $line = “My name is Jack.”; if($line =~ m/Jack\.$/) {

print “End of line is Jack.”; }

Match A Number Of A Certain Format $str = “Cost: \$40,999.95”; if ($str =~ /\$\d+,?\d*\.?\d*/) {

print “Matches”; }

Page 67: Perl Training Cvs

Pattern MatchingMore Regular Expression Examples

/abc*/ # ab, abc, abcc, abccc, abcccc …

/b{3}/ # three b's/\w{5}/ # 5 word characters in a row/de{1,2}f/ # def or deef/de{3,}/ # d followed by at least 3 e’s/\w{2,8}/ # match 2 to 8 word characters

Regular Expressions - Word Boundary Examples/fred\b/ # fred, but not frederick

/\bmo/ # moe and mole, but not Elmo

/\bFred\b/ # Fred but not Frederick or alFred

/\Bfred/ # matches abcfred, but not fred/def\B/ # matches defghi/\Bfred\B/ # cfredd but not fred, fredrick, or alfred

Page 68: Perl Training Cvs

GroupingGrouping

Parentheses are used for grouping.Parentheses also have the side effect of remembering what they matched. We will look into this ability later.Use a pipe (vertical bar) to separate two or more alternatives.

Example$text = “I’m busy today!”;if ($text =~ /bus(y|ied|ier|isest)?/) { # match: busy, busied, busier, or busiest

print “Matches”; }

More Regular Expression Grouping Examples/(abc)+/ # match: abc, abcabc, abcabcabc

…/^(x|y)/ # match either x or y at beginning of a line/(a|b)(c|d)/ # match: ac, ad, bc, or bd

Page 69: Perl Training Cvs

GroupingGrouping can also be used without parentheses when you just trying to match a series of words.

/now|then/ # matches ‘now’ or ‘then’/^There|^Their/ # matches ‘There’ or ‘Their’ at the beginning of a line

Grouping example using array elements as the search patterns:@patterns = qw(exit quit goodbye);$pattern = join(“|", @patterns); # create string: exit|quit|goodbyewhile($line = <>) {

if ($line =~ /$pattern/) { # look for “exit”, “quit” or “goodbye”print “You entered: exit, quit or goodbye\n”; exit;

} else {print “You entered: $_\n”;

}}

Page 70: Perl Training Cvs

Character ClassesCharacter Classes

A pattern-matching character class is represented by a pair of open and close square brackets and a list of characters between the brackets.

Only one of the characters must be present at the corresponding part of the string for the pattern to match.

Specify a range of characters with the “-” character.Backslashes apply inside character classes.

Examples$text = “Here he is.”;if ($text =~ /[aeiou]/) { # match any single vowel

print “There are vowels.\n”; }

$text2 = “-3.1415”;if($text2 =~ /^[+-][0-9]+\.\d*$/) {

print “It’s correct.”; }

Page 71: Perl Training Cvs

Character ClassesNegated Character Classes

There's also a negated character class that matches any character not in the list.Create a negated character class by placing a caret ‘^’immediately after the left bracket.

Example$text = “Hello”;if ($text =~ /[^aeiou]/i) { # match any single non-vowel

print “There are consonants”;}

Page 72: Perl Training Cvs

Coding time#!/usr/intel/bin/perl

# This script validates variable names.

print “Enter a variable name: ”;

chomp($var = <STDIN>);

if ($var =~ /^\$[A-Za-z][_0-9A-Za-z]*$/) {

print “$var is a legal scalar variable.\n”;

} elsif ($var =~ /^@[A -Za-z][_0-9A-Za-z]*$/) {

print “$var is a legal array variable.\n”;

} elsif ($var =~ /^%[A -Za-z][_0-9A-Za-z]*$/) {

print “$var is a legal hash variable.\n”;

} else {

print “$var is not a legal variable.\n”;

}

Page 73: Perl Training Cvs

BackreferencingBackreferencing Examples (Outside Regular Expressions)$text = “David is 20 years old.”;if ($text =~ /(\d+)/) {

print “He is $1 years old.\n”; => He is 20 years old.}

$text = “I am busy today!”;$text =~ /^(\w+)\s+(\w+)\s(\w+)/;print “$1 $2 $3!”; => I am busy!

Page 74: Perl Training Cvs

Pattern SubstitutionIn addition to matching patters, regular expressions can be usedto substitute matched patterns.

Basic Substitution Example$var =~ s/error/warning/g;

In this example, Perl substitutes any occurrences of the ‘error’string inside of the $var variable with the ‘warning’ string.The s// operator is the substitution operator. It tells Perl to search for the pattern specified in its first two delimiter’s and replace that pattern with the pattern specified in its second two delimiter’s. The value inside the $string variable gets modified if a match is found.The substitution operator’s ‘s’ prefix is required.

Page 75: Perl Training Cvs

Pattern SubstitutionAll the previous operators, modifiers, assertions and so on, work with pattern substitution as well.

Basic Examples$text = “I’m pretty young.”;$text =~ s/young/old/;print $text; => I’m pretty old.

$text = “I’m young and you’re young.”;$text =~ s/young/old/;print $text; => I’m old an you’re young.

Page 76: Perl Training Cvs

Pattern SubstitutionMore Basic Examples

$text = “Here he is.”;$text =~ s/\w+/There/;print $text; => There he is.

Note: Use “+” to match the whole word.$text = “Today is Tuesday.”;$text =~ s/./*/g;print $text; => *****************$text = “How are youuuuuuu?”;$text =~ s/u+/u/g;print $text; => How are you?

Page 77: Perl Training Cvs

Pattern SubstitutionMore Basic Examples

$string = "hello, world"; $new = "goodbye"; $string =~ s/hello/$new/; print $string; => goodbye, world

$text = “Perl is on page 493.”;$text =~ s/[^A-Za-z\s]+/500/;print $text; => Perl is on page 500.

Page 78: Perl Training Cvs

Pattern SubstitutionObtaining The Number Of Substitutions Made

$text = “How are youuuu?”;$subs = ($text =~ s/u/z/g);print $subs; => 4

Backreferencing With Pattern Substitution$text = “snakes eat rabbits”;$text =~ s/^(\w+) *(\w+) *(\w+)/$3 $2 $1/;print $text; => rabbits eat snakes

Page 79: Perl Training Cvs

Pattern SubstitutionRemove Leading & Trailing White Space

$text = “ I’m leaving.”;$text =~ s/^\s+//;print $text; => I’m leaving.$text = “I’m leaving. “;$text =~ s/\s+$//;print $text; => I’m leaving.

Page 80: Perl Training Cvs

Example Script#!/usr/intel/bin/perl

# This script cleans up white space. It removes all extraneous leading spaces and tabs,

# and replaces multiple spaces and tabs between words with a single space.

while(<>) {

last if(/^\s*$/); # exit loop if nothing entered on input lines/^\s+//; # leading white spaces/\s+$//; # trailing white spaces/\s+/ /; # mid white spacepush (@var, $_); # add modified line to @var array

}print "Formatted text: \n";print "@var";

Page 81: Perl Training Cvs

Pattern TranslationBasic Examples of translation

$text = “Hello Tammy.”;$text =~ tr/a/o/; # translate a’s into o’sprint $text; => Hello Tommy.$text =~ tr/Tm/Dn/;print $text; => Hello Donny.$text =~ tr/a-z/A-Z/; # upper case everythingprint $text; => HELLO DONNY.$O_count = ($text =~ tr/O/O/); # Count the number of O’s in $text.print $text; => HELLO DONNYprint $O_count; => 2Notice the usage of “=“ vs “=~”.

Page 82: Perl Training Cvs

Pattern TranslationBasic Examples Using The Options (d)

Delete found but unreplaced characters (d)$text2 = “zed sandy tabey”;$text2 =~ tr/a-z/A-N/d;print $text2; => ED AND ABE

Note: Spaces were unaffected because they didn’t appear in the old list search pattern.

$letters =~ tr/AEIOU/ae/d;Replace every A and E to a and e respectively, but deletes every I, O, and U found in $letters.

Page 83: Perl Training Cvs

Exercises

• What do the following RE’s match?a) /\\*\**/ e) /abc{1,4}/b) /\bc[aou]t\b/ f) /ab*c/c) /a|bc*/ g) /^hello|adios$/d) /(xy+z)\.\1/ h) /^(hello|adios)$/

Page 84: Perl Training Cvs

Exercises• If $var = “abc123”, indicate whether the following conditional

expressions return true or false:a) $var =~ /./;b) $var =~ /\w{3,6}/;c) $var =~ /abc$/;If $var = “abc123abc”, what is the value of $var after the following substitutions:a) $var =~ s/abc/def/;b) $var =~ s/B/W/i;

Page 85: Perl Training Cvs

Subroutines

Page 86: Perl Training Cvs

Agenda

Subroutine IntroPassing ArgumentsDefault ValuesReturn ValuesVariable ScopeExercises

Page 87: Perl Training Cvs

Subroutine IntroA subroutine is a block of code separate from your main program, designed to perform a particular task.

A subroutine is basically a user-defined function.Once written, they can be used just like the built-in Perl functions such as join or chomp.

The idea behind subroutines is divide and conquer. Subroutines allow you to divide your code into manageable parts, making the overall programming easier to write and maintain.

Other benefits to writing subroutines are: They help to avoid writing repetitive code in a programThey make debugging easierThey can be reused in other programs

Page 88: Perl Training Cvs

Subroutine Intro#!/usr/intel/bin/perl

# Obtain inputted numbers & print the total value.$total = 0;getnumbers(); # call subroutine that grabs inputforeach $number (@numbers) {

$total += $number;}print “The total is $total\n”;# Subroutine to grab inputted numbers.sub getnumbers {

$line = <STDIN>; # get input$line =~ s/^\s+|\s*\n$//g; # removing leading & trailing white space@numbers = split(/\s+/, $line);# break input into numbers & place in array

}

Page 89: Perl Training Cvs

Passing Arguments

#!/usr/intel/bin/perl# Example of passing multiple arguments to a subroutine.$title = “Hannibal”;$author = “Thomas Harris”;fav_book($title, $author); # call subroutine & pass arguments

# Subroutine to print favorite book.sub fav_book {

print “My favorite book is $_[0] by $_[1]\n”;}

=> My favorite book is Hannibal by Thomas Harris

Page 90: Perl Training Cvs

Passing Arguments

#!/usr/intel/bin/perl# Example of passing an array.@bookInfo = ("Hannibal", "Thomas Harris");fav_book(@bookInfo); # call subroutine & pass arguments

# Subroutine to print favorite book.sub fav_book {

print "My favorite book is $_[0] by $_[1]\n";}

=> My favorite book is Hannibal by Thomas Harris

Page 91: Perl Training Cvs

Passing Arguments

#!/usr/intel/bin/perl# Another example. Passing an array & an integer.@array = (3, 3);add_all(@array, 3); # call subroutine & pass @array

# Function to sum passed values.sub add_all {

$sum = 0;foreach $element (@_) {

$sum += $element;}print “The total is $sum\n”; => The total is 9.

}

Page 92: Perl Training Cvs

Passing ArgumentsNote when used in a subroutine, the shift function defaults to working on the @_ array.

#!/usr/intel/bin/perl# Example of passing an array.@bookInfo = ("Hannibal", "Thomas Harris");fav_book(@bookInfo); # call subroutine & pass arguments# Subroutine to print favorite book.sub fav_book {

$book = shift; # grab first argument & place in $book$author = shift; # grab second argument & place in

$authorprint "My favorite book is $book by $author\n";

}=> My favorite book is Hannibal by Thomas Harris

Page 93: Perl Training Cvs

Return ValuesWhen the subroutine completes, data can be returned to the main program with the return keyword.

Subroutines can return scalar or list values.Perl will exit from a subroutine immediately after the return statement executes.Any code in the subroutine that appears after the returnstatement does not get executed.

The value of the last expression evaluated by the subroutine is automatically considered the return value if the returnkeyword is not used.To ensure the correct return value from a subroutine, use the return keyword.

Page 94: Perl Training Cvs

Return Values#!/usr/intel/bin/perl$name = “Rocky”;$years_old = “3”;$years = dog_years($years_old); # call subroutine, return value

# placed in $years variableprint “My dog $name is $years dog years old.”;

# subroutine to compute dog yearssub dog_years {

$yrs_old = shift;$age = 7 * $yrs_old; # compute agereturn $age; # return value in $age

}

Page 95: Perl Training Cvs

Return Values#!/usr/intel/bin/perl# Example of returning a list/array from a subroutine.

@values = dumb_sub(“a”, “b”);print “I passed @values.”; => I passed a b .

sub dumb_sub {return (@_); # return passed arguments

}

Page 96: Perl Training Cvs

Return Values#!/usr/intel/bin/perl# Second example of returning a list/array from a subroutine.

($first, $last) = list_sub();print “President $first $last\n”; => President George Bush

sub list_sub {return (“George”, “Bush”); # return a list of arguments

}

Page 97: Perl Training Cvs

Return Values#!/usr/intel/bin/perl# Example of returning a hash from a subroutine.

%ssn = name_ssn();foreach $key (keys %ssn) {print “$key -> $ssn{$key}\n";

}sub name_ssn {return ( # return a hash of name=>SSN

pairs“John Smith” => 441-36-0889,“Jane Doe” => 104-21-2094,“Dave Bishop” => 394-84-2940,

);}

Page 98: Perl Training Cvs

Return Values#!/usr/intel/bin/perl# Example of using multiple return statements in a subroutine.$result = arithmetic(“plus”, 2, 2);print “Result is: $result\n”; => Result is: 4

sub arithmetic {$operation = shift;$arg1 = shift; $arg2 = shift;if($operation eq “plus”) {return $arg1 + $arg2; # return sum of values} elsif($operation eq “minus”) {return $arg1 - $arg2; # return remainder of values

} else {return $arg1 * $arg2; # return product of values}}