510 likes | 817 Views
Basic Perl Programming. Introduction: Perl - Practical Extraction and Report Language Using interpreter to run on the system (windows/unix/linux perl interpreter) Very powerful for handling and manipulate text Usually with *.pl file/script extension. Getting Perl.
E N D
Basic Perl Programming Introduction: Perl - Practical Extraction and Report Language Using interpreter to run on the system (windows/unix/linux perl interpreter) Very powerful for handling and manipulate text Usually with *.pl file/script extension
Getting Perl • In Linux/Unix OS it has become a standard package installed • For Windows OS get it from: • http://www.activestate.com/ • http://strawberryperl.com/
Basic Perl Programming My first Perl program (Say hello to Perl) #! /usr/bin/perl # print a words "Say hello to Perl" print "Say hello to Perl.\n";
Basic Perl Programming Basic Standard Input/Output #! /usr/bin/perl print "\nPlease enter your name: "; $user_name = <STDIN>; print "\nHello ", $user_name, "Please say hello to Perl\n";
Basic Perl Programming Variable (Scalar) must be preceded with ‘$’ sign no specific data types (int, float, char) #! /usr/bin/perl $food = "2-Piece Chicken"; $drink = "Pepsi"; print "Food = $food\n"; print "Drink = $drink\n\n"; $food = 4.59; $drink = 1.7; print "Food price= $food\n"; print "Drink price= $drink\n"; print "Total price= ", $drink + $food, "\n";
Basic Perl Programming Exercise 1: Write Perl script to ask student to enter name, e-mail, and course. The script will later print out all the information entered.
Basic Perl Programming Variable (Array) preceded with ‘@’ sign several ways to define array: @food = (“”); $food[0] = “2-Piece Chickens”; $food[1] = “Kentucky Nuggets (6 Pieces)”; $food[2] = “Deli Burger”; @drink = (“Pepsi”, “Ice Lemon Tea”, “Orange Juice”);
Basic Perl Programming Variable (Array) syntax to get an array element:$array_variable_name[index_value]; retrieve the number of item and length of index of array variable: $items = @drink # $ items will get the value of 3 $length = $#drink # $length will get the value of 2
Basic Perl Programming Variable (Array) define and assign a value of array variable using split function $f_price = “4.59 3.99 2.00”; @food_price = split(/ /, $f_price); @drink_price = split(/:/, “1.70:2.20:2.20”);
Basic Perl Programming Exercise 2: Modify the script from exercise 1 so it can handle more than single student information.
Basic Perl Programming Variable (Hash) • a series pairs of keys and values • Preceded with “%” sign • The syntax to define hash:%hash_var = ( key_1 => “value_1”, … , key_n => “value_n”);
Basic Perl Programming • Variable (Hash) • The other possible way to assign keys and values to hash:%hash_var = undef;$hash_var{key_1} = “value_1”;…$hash_var{key_n} = “value_n”;
Basic Perl Programming Variable (Hash) Example: %food = (""); $food{fruit} = "Apple"; $food{animal} = "Beef"; %drink =(natural=>"Mineral Water", carbonate=>"Coca-Cola");
Basic Perl Programming Variable (Hash) syntax to get hash element:$hash_var_name{key}; get all keywords from hash and store it in an array @array_var_name = keys(%hash_var_name);
Basic Perl Programming • Variable (Hash) • Access hash keys name:@keys = keys(%hash_var);print "\$keys[0] = $keys[0] \n";print "\$keys[1] = $keys[1] \n";print "\$keys[.] = $keys[.] \n";print "\$keys[n] = $keys[n] \n";
Basic Perl Programming • Variable (Hash) • Access and assign value to specific hash key:print “$keys[0]= ” , $hash_var{$keys[0]}, “\n”;$hash_var{$keys[0]} = “other value”;print “$keys[0]= ” , $hash_var{$keys[0]}, “\n”;
Basic Perl Programming • Copying,Referencing & De-referencing Variable • Copying variable:$my_var = “hello”;$other_var = $my_var; • print “$my_var : $other_var \n”; • $other_var = “olleh”; • print “$my_var : $other_var \n”;
Basic Perl Programming • Referencing & de-referencing variable:$my_var = “hello”;$other_var = \$my_var; • print “$my_var : $$other_var \n”; • $$other_var = “olleh”; • print “$my_var : $$other_var \n”;
Basic Perl Programming • Explanations:$other_var = \$my_var; -> this will caused $other_var store the address refer by $my_var • $$other_var; -> this is the way we assign/access the value • stored by the address • $$other_var = “olleh”; -> this will caused address refer by both $my_var & $other_var had a new value (“olleh”)
Basic Perl Programming • Referencing & de-referencing array & hash:@my_array = (“One”, “Two”);%my_hash = (1 => “One”, 2 => “Two”);$array_ref = \@my_array;$hash_ref = \%my_hash;#de-referencing array & hash${$array_ref}[0] or $array_ref->[0];${$hash_ref}{2} or $hash_ref->{2}; • #copy array & hash from reference • @other_array = @{$array_ref}; • %other_hash = %{$hash_ref};
if (…){} Executes when a specified condition is true Basic Perl Programming if (…) {} else {} Chooses between two alternatives if (…){} elsif() {} else {} Chooses between more than two alternatives for (…) {} Repeats a group of statements a specified number of times foreach $var_name1 (@var_name2) Special loop to access all elements in array variable while(…) {} Repeats a group of statements a specified number of times Loop and control statement
Operator Description Basic Perl Programming < Less than > Greater than == Equal to <= Less than or equal to >= Greater than or equal to != Not equal to Integer-Comparison Operators Comparison Operators
Operator Description lt Less than gt Greater than eq Equal to le Less than or equal to ge Greater than or equal to ne Not equal to Comparison Operators Basic Perl Programming String-Comparison Operators
Basic Perl Programming Exercise 3: Extend the script from exercise 2 so it can handle other new input (student’s CPA). Based on the CPA value determine either they get 1st, 2nd, or 3rd class following the given conditions below:
Basic Perl Programming Pattern matching and string manipulation The syntax for pattern matching: $string_variable=~/pattern_to_match/opt; Example: $str = “Hello World”; if ($str =~ /lo/) { print “Found it.\n”; } else { print “Not found.\n”; }
Basic Perl Programming Pattern matching and string manipulation The syntax for pattern replacement: $string_variable=~s/pattern_to_replace/replacement/opts; Example: $str = “Hello World”; $str =~ s/l/m/g;
Option Description g Change all occurrences of the pattern i Ignore case in pattern e Evaluate replacement string as expression (only for substitution operator) m Treat string to be matched as multiple lines o Evaluate only once s Treat string to be matched as single line x Ignore white space in pattern Basic Perl Programming Pattern matching and string manipulation Options (opts) for pattern matching & replacement
Basic Perl Programming Pattern matching and string manipulation Regular expression in the pattern (pattern_to_replace) Meta-characters To present these meta-characters as a character itself use the ‘\’ character before each meta-characters. Examples: \^, \$, … http://www.cs.tut.fi/~jkorpela/perl/regexp.html
Basic Perl Programming How to know if the string hold by the scalar $plate_no is a valid Johor’s car plate number? - All letters must be capital start with ‘J’ ^J - The trailing letters not more than 2 and not including the ‘I’, ‘O’, and ‘Z’ letters ^J[A-H,J-N,P-Y]{1,2} - Ending with numbers not starting with ‘0’ and not more than 4 in total ^J[A-H,J-N,P-Y]{1,2}[1-9]{1}[0-9]{0,3} Pattern matching and string manipulation Regular expression in the pattern (pattern_to_replace)
Function Description index (string, substring) Identify the location of a substring in a string. rindex (string, substring) Similar to the index function but starts searching from the right end of the string. length (string) Returns the number of characters contained in a character string. substr (string, num_of_skip_char, length) Returns a part of a character string. lc(string) Converts a string to lowercase. uc(string) Converts a string to uppercase. Basic Perl Programming Pattern matching and string manipulation String manipulation functions
Basic Perl Programming Pattern matching and string manipulation String concatenation: #! /usr/bin/perl $string1 = “The first string ”; $string2 = “The second string”; $my_string = $string1 . “ and ” . $string2 ; print “$my_string \n”;
Basic Perl Programming File Input/Output Read Operation: if(open(MYFILE, "<directory/file_name")){ @array_var = <MYFILE>; . . . . . . . . . close(MYFILE); }
Basic Perl Programming File Input/Output Write Operation: if(open(MYFILE, “>directory/file_name")) { . . . . . . . . . print MYFILE ($var_store_file_content); close(MYFILE); }
Basic Perl Programming Exercise 4: Modify the script from exercise 3 so the output would also be available as an HTML file. Use the template below as a basic structure of the HTML file content. <html> <body> <table> <tr><td>Name</td><td>CPA</td><td>Class</td></tr> <tr><td>_name_</td><td>_cpa_</td><td>_class_</td></tr> </table> </body> </html>
Basic Perl Programming Subroutine/Function Create a subroutine in Perl script : sub subroutine_name { . . . . . . . . . } Calling a subroutine: &subroutine_name;
Basic Perl Programming Subroutine Skeleton of perl script that using a subroutine: #! /usr/bin/perl . . . . . . &subroutine_name; . . . . . . sub subroutine_name { . . . . . . }
Basic Perl Programming Subroutine Example: #! /usr/bin/perl print "Perl script welcoming the users.\n\n"; &welcome_user; sub welcomeUser { print "Your name please: "; $name = <STDIN>; chop($name); print "\nHello $name, welcome to Perl world.\n\n"; }
Basic Perl Programming Subroutine Pass and return values to/from subroutine make a subroutine more flexible and useful based on three guidelines : The subroutine can accept more than one scalar variable and only one array variable If the subroutine accept both scalar and array variables the array variable must appear last in the arguments The first two guidelines above can be ignored by passing array/hash as a reference
Basic Perl Programming Subroutine Pass and return values to/from subroutine The Skeleton: sub subroutine_name { $scalar_var_name_1 = shift @_; . . . $scalar_var_name_n = shift @_; @array_var_name = @_; . . . . . . return (value); }
Basic Perl Programming Subroutine Pass and return values to/from subroutine Calling a subroutine that can accept and return values: $var_name = &subroutine_name(scalar1, . . ., scalarN, array);
Basic Perl Programming Subroutine Pass and return values to/from subroutine The story so far: To return a value the command: return (value); is used inside the subroutine where value can be either scalar, array or result of an expression When values passed to the subroutine, all the values are stored in the special array variable named @_ The subroutine must extract all the values from this special array variable and pass it to the appropriate variables following the guidelines given previously
Basic Perl Programming Subroutine Pass and return values to/from subroutine The story so far: To return a value the command: return (value); is used inside the subroutine where value can be either scalar, array or result of an expression When values passed to the subroutine, all the values are stored in the special array variable named as: @_ The subroutine then must extract all the values from this special array variable and pass it to the appropriate variables using the two guidelines above
Basic Perl Programming Subroutine Pass and return values to/from subroutine The story so far: The command: shift @_; will extract and shift the first item in @_ The command: @array_var_name = @_; will assigns all the values of @_ to @array_var_name Example: Variable @_ contains the values: (“A”, “B”, “C”) The command $var_name = shift @_ will extract the first item of @_ which is “A”, pass it to $var_name and left the @_ with the values: (“B”, “C”) The next command @var_name2 = @_ will make the variable @var_name2 contains the values: (“B”, “C”)
Basic Perl Programming Exercise 5: Modify the script from exercise 4 so the core tasks are written modularly using subroutines/functions.
Basic Perl Programming Subroutine Writing subroutines as a libraries The technique for writing a subroutine before caused the subroutine can only be used by the script who implementing them Writing subroutines as a libraries provide more flexible subroutine that can be used many times by other scripts
Basic Perl Programming Subroutine Writing subroutines as a libraries Skeleton for writing subroutine as a libraries: package library_name; subroutines goes here . . . 1; The scripts that are intended to be a libraries must be saved as library_name.pl The: 1; at the end of libraries script is a mandatory so the perl interpreter can call and run the libraries correctly
Basic Perl Programming Subroutine Writing subroutines as a libraries Calling and use subroutine from the libraries: #! /usr/bin/perl require (“library_name.pl"); . . . $val = &library_name’subroutine_name1; &library_name’subroutine_name2(. . .); . . .
Basic Perl Programming #! /usr/bin/perl $name = "Your name"; print "\$name: $name\n"; &change_name; print "\Sname: $name\n"; sub change_name { my $name = "My name"; } #! /usr/bin/perl $name = "Your name"; print "\$name: $name\n"; &change_name; print "\Sname: $name\n"; sub change_name { $name = "My name"; } Subroutine Variable scope: