Presentation is loading. Please wait.

Presentation is loading. Please wait.

Basic Perl Programming

Similar presentations


Presentation on theme: "Basic Perl Programming"— Presentation transcript:

1 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

2 Getting Perl In Linux/Unix OS it has become a standard package installed For Windows OS get it from:

3 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";

4 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";

5 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";

6 Basic Perl Programming
Exercise 1: Write Perl script to ask student to enter name, , and course. The script will later print out all the information entered.

7 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”);

8 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 # $ items will get the value of 3 $length = $#drink # $length will get the value of 2

9 Basic Perl Programming
Variable (Array) define and assign a value of array variable using split function $f_price = “ ”; @food_price = split(/ /, $f_price); @drink_price = split(/:/, “1.70:2.20:2.20”);

10 Basic Perl Programming
Exercise 2: Modify the script from exercise 1 so it can handle more than single student information.

11 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” );

12 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”;

13 Basic Perl Programming
Variable (Hash) Example: %food = (""); $food{fruit} = "Apple"; $food{animal} = "Beef"; %drink =(natural=>"Mineral Water", carbonate=>"Coca-Cola");

14 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);

15 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";

16 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”;

17 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”;

18 Basic Perl Programming
Referencing & de-referencing variable: $my_var = “hello”; $other_var = \$my_var; print “$my_var : $$other_var \n”; $$other_var = “olleh”;

19 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”)

20 Basic Perl Programming
Referencing & de-referencing array & hash: @my_array = (“One”, “Two”); %my_hash = (1 => “One”, 2 => “Two”); $array_ref = $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 %other_hash = %{$hash_ref};

21 Loop and control statement
Basic Perl Programming Loop and control statement if (…){} Executes when a specified condition is true 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 Special loop to access all elements in array variable while(…) {}

22 Basic Perl Programming
Comparison Operators Integer-Comparison Operators Operator Description < Less than > Greater than == Equal to <= Less than or equal to >= Greater than or equal to != Not equal to

23 Basic Perl Programming
Comparison Operators String-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

24 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: CPA Class 3.7 and above 1st 2.0 – 3.69 2nd Below than 2.0 3rd

25 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”; }

26 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;

27 Basic Perl Programming
Pattern matching and string manipulation Options (opts) for pattern matching & replacement 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

28 Basic Perl Programming
Pattern matching and string manipulation Regular expression in the pattern (pattern_to_replace) Meta-characters Char Meaning ^ beginning of string ? match 0 or 1 times $ end of string | alternative . any character except newline () grouping * match 0 or more times [] set of characters + match 1 or more times {} repetition modifier To present these meta-characters as a character itself use the ‘\’ character before each meta-characters. Examples: \^, \$, …

29 Basic Perl Programming
Pattern matching and string manipulation Regular expression in the pattern (pattern_to_replace) 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}

30 Basic Perl Programming
Pattern matching and string manipulation String manipulation functions 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.

31 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”;

32 Basic Perl Programming
File Input/Output Read Operation: if(open(MYFILE, "<directory/file_name")){ @array_var = <MYFILE>; . . . close(MYFILE); }

33 Basic Perl Programming
File Input/Output Write Operation: if(open(MYFILE, “>directory/file_name")) { . . . print MYFILE ($var_store_file_content); close(MYFILE); }

34 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>

35 Basic Perl Programming
Subroutine/Function Create a subroutine in Perl script : sub subroutine_name { . . . } Calling a subroutine: &subroutine_name;

36 Basic Perl Programming
Subroutine Skeleton of perl script that using a subroutine: #! /usr/bin/perl . . . &subroutine_name; sub subroutine_name { }

37 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"; }

38 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

39 Basic Perl Programming
Subroutine Pass and return values to/from subroutine The Skeleton: sub subroutine_name { $scalar_var_name_1 = . . . $scalar_var_name_n = @array_var_name return (value); }

40 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);

41 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

42 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 then must extract all the values from this special array variable and pass it to the appropriate variables using the two guidelines above

43 Basic Perl Programming
Subroutine Pass and return values to/from subroutine The story so far: The command: will extract and shift the first item The will assigns all the values Example: contains the values: (“A”, “B”, “C”) The command $var_name = will extract the first item which is “A”, pass it to $var_name and left with the values: (“B”, “C”) The next will make the contains the values: (“B”, “C”)

44 Basic Perl Programming
Exercise 5: Modify the script from exercise 4 so the core tasks are written modularly using subroutines/functions.

45 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

46 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

47 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(. . .);

48 Basic Perl Programming
Subroutine Variable scope: #! /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"; }


Download ppt "Basic Perl Programming"

Similar presentations


Ads by Google