Basic Perl Programming

Slides:



Advertisements
Similar presentations
Chapter 25 Perl and CGI (Common Gateway Interface)
Advertisements

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
A Guide to Unix Using Linux Fourth Edition
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Second edition Your UNIX: The Ultimate Guide Das © 2006 The McGraw-Hill Companies, Inc. All rights reserved. UNIX – The Master Manipulator perl Perl is.
Introduction to C Programming
Programming and Perl for Bioinformatics Part III.
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
CS311 – Today's class Perl – Practical Extraction Report Language. Assignment 2 discussion Lecture 071CS Operating Systems I.
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
PERL Part 3 1.Subroutines 2.Pattern matching and regular expressions.
Practical Extraction & Report Language Picture taken from
1ex.1 Perl Programming for Biology Exercise 1 The Bioinformatics Unit G.S. Wise Faculty of Life Science Tel Aviv University, Israel March 2009 Eyal Privman.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
Computer Programming for Biologists Class 2 Oct 31 st, 2014 Karsten Hokamp
Introduction to Perl Thaddeus Aid IT Learning Programme University of Oxford 15/04/2014.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Introduction to Perl & BioPerl Dr G. P. S. Raghava Bioinformatics Centre Bioinformatics Centre IMTECH, Chandigarh Web:
Computer Programming for Biologists Class 5 Nov 20 st, 2014 Karsten Hokamp
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Introduction To Perl Susan Lukose. Introduction to Perl Practical Extraction and Report Language Easy to learn and use.
4 1 Array and Hash Variables CGI/Perl Programming By Diane Zak.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
Open Source Software Unit – 3 Presented By Mr. R.Aravindhan.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CS 330 Programming Languages 10 / 07 / 2008 Instructor: Michael Eckmann.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Introduction to Perl Yupu Liang cbio at MSKCC
What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports.
Perl Language Yize Chen CS354. History Perl was designed by Larry Wall in 1987 as a text processing language Perl has revised several times and becomes.
Perl: Lecture 1 The language. What Perl is Merger of Unix tools – Very popular under UNIX – shell, sed, awk Programming language – C syntax Scripting.
Chapter 9: Perl Programming Practical Extraction and Report Language Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Chapter 9: Perl (continue) Advanced Perl Programming Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Introduction to Unix – CS 21
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
CS 330 Programming Languages 10 / 02 / 2007 Instructor: Michael Eckmann.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Perl Basics. sh-bang !!!! Every perl program starts with a sh-bang line #!/usr/bin/perl # hello.pl printf “Hello, world!\n”; printf STDOUT “Hello, world!\n”;
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
LING/C SC/PSYC 438/538 Lecture 8 Sandiway Fong. Adminstrivia Homework 4 not yet graded …
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.
More Perl Data Types Scalar: it may be a number, a character string, or a reference to another data type. -the sigil $ is used to denote a scalar(or reference)
Introduction to Perl NICOLE VECERE. Background General Purpose Language ◦ Procedural, Functional, and Object-oriented Developed for text manipulation.
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
IS2802 Introduction to Multimedia Applications for Business Lecture 4: JavaScript, Loops, and Conditional Statements Rob Gleasure
8 1 String Manipulation CGI/Perl Programming By Diane Zak.
PERL By C. Shing ITEC Dept Radford University. Objectives Understand the history Understand constants and variables Understand operators Understand control.
Strings, Characters, and Regular Expressions Session 10 Mata kuliah: M0874 – Programming II Tahun: 2010.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
The Scripting Programming Language
PZ02CX Programming Language design and Implementation -4th Edition Copyright©Prentice Hall, PZ02CX - Perl Programming Language Design and Implementation.
Dept. of Animal Breeding and Genetics Programming basics & introduction to PERL Mats Pettersson.
CS 330 Programming Languages 09 / 30 / 2008 Instructor: Michael Eckmann.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Information and Computer Sciences University of Hawaii, Manoa
CS 330 Class 7 Comments on Exam Programming plan for today:
Perl Programming Language Design and Implementation (4th Edition)
Chapter 19 PHP Part II Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
Intro to PHP & Variables
Topics Introduction to File Input and Output
PHP.
The Selection Structure
Topics Introduction to File Input and Output
CIS 136 Building Mobile Apps
Presentation transcript:

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

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

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

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 (@var_name2) Special loop to access all elements in array variable while(…) {}

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

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

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

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;

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

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: \^, \$, … http://www.cs.tut.fi/~jkorpela/perl/regexp.html

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}

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.

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