1 / 66

Introduction to PERL

Introduction to PERL. Nick Gould N.Gould@man.ac.uk. Aim of Course . Provide gentle introduction to Perl Combination of lecture and hands-on Can’t learn Perl in a day But should have enough to assess whether Perl is suitable for your needs. Topics. Branching Looping Arrays File Handling

alden
Download Presentation

Introduction to PERL

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to PERL Nick Gould N.Gould@man.ac.uk

  2. Aim of Course • Provide gentle introduction to Perl • Combination of lecture and hands-on • Can’t learn Perl in a day • But should have enough to assess whether Perl is suitable for your needs.

  3. Topics • Branching • Looping • Arrays • File Handling • Pattern Matching • Subroutines

  4. Topics /contd • Accessing UNIX • Command Line • Common Errors

  5. Where to Find Perl • Usually at /usr/bin/perl • or /usr/local/bin

  6. What is Perl? • Practical Extraction and Report Language • Interpreted language • Similar to C • Developed by Larry Wall at end of 80s • Current version is 5. • Many platforms • UNIX, NT, VMS, MS-DOS, MVS, Mac

  7. Why use Perl? • Easy to write and execute programs • Not rigorous unlike C • pros and cons • Useful for • System admin • WWW scripts (see course in January) • Data manipulation

  8. A Simple Perl Program #!/usr/bin/perl # this is a simple perl program $name= “Hello”; print (“$name\n”); Entered in file - first.pl

  9. Running Perl Programs • Type perl followed by filename • $ perl first.pl

  10. What Happens? • Syntax Checked • Executed • All with one command

  11. Perl Errors • When Perl comes across a syntax error - Error Message returned • Will not execute if there are syntax errors.

  12. Scalar Variables • always start with $ • Not declared • No naming distinction between numeric and string • $x = 47; • $x = “A String.”; • Naming rules

  13. Input • To read in from keyboard • $line = <STDIN>;

  14. The Chop Function • $line = <STDIN>; • $line includes newline at end of string • Use chop function to remove it. chop ($line);

  15. Doing Sums • Arithmetic operators • + add • - subtract • * multiply • / divide • $x = $y / $z;

  16. Strings and Things • Print function $result = 345; print (“The result is $result\n”); print (“The result is ”,$result, ”\n”); The result is 345

  17. Escape Characters • \n newline • \t tab • \L all following letters lowercase • \$ to print the “$” • print (“The value of \$result is $result\n”);

  18. Control Constructs

  19. Branching - If Statement if ($x == $y) { print (“The numbers are equal”); } Print (“Done.\n”); • If expression true evaluate code in { }

  20. If...Else Statement if ($x == $y) { print (“The numbers are equal\n”); }else{ print (“The numbers are unequal\n”); } Print (“Done.\n”); • Provides alternative if expression false.

  21. If...Elsif...Else if ($x > $y) { print (“x is greater than y”); }elsif ($x < $y) { print (“y is greater than x\n”); }else{ print (“the two numbers are equal\n”); } Print (“Done.\n”); • can have any number of elsifs

  22. Comparison Operators • Arithmetic == > < >= <= != • String eq gt lt ge le ne • NB Don’t mix them up or confuse with assignment (=)

  23. Logical Operators • And && • Or || • Not ! ($x < 20 && $x > 13) • True if x is between 13 and 20. • ($ans eq “Y” || $ans eq “y”)

  24. What is true? • In Perl every value is considered to be true, except for : • null string (“”) • 0 (numeric value) • “0” (string value) • 0.0 false as number, true as string.

  25. Two Common Errors print("Exit program? Enter yes or no -"); $response =<STDIN>; if ($response = "yes") { die ("Quit on user request"); } print ("Program continuing...\n");

  26. Looping - While $count=0; while ($count < 5) { $count = $count+1; print ("count is $count\n"); } • While expression is true execute code in { }

  27. Incrementing • $count = $count + 1; • $count +=1; • $count++; • ++$count; • All increment $count

  28. Auto - Increment • Pre and post • $y = ++$x; increment then assign • $y = $x++; assign then increment • Can be confusing

  29. Until Loop • While - loops while true • Until - loops until true $x = <STDIN>; chop ($x); until ($x == 24) { $x=<STDIN>; chop $x; }

  30. For Loop for ($count=1; $count<=5;$count++) { print ("count is $count\n"); } • More readable than while • avoids problem with missing counter

  31. Perl Operators • . Concatenation • x Repeat • http://www.codebits.com/p5be/ch04.cfm

  32. Perl Functions • Array: • chop chomp • join split splice • pop push • shift unshift • reverse sort • http://www.codebits.com/p5be/xp0c.cfm

  33. Accessing the UNIX System • $return = `unix_command`; • ` is backquote • Example • $files= `ls`; • $files contains list of files

  34. Arrays

  35. Perl Data Structures • Scalars • one value per name • identifiers begin with $ • Arrays of scalars • identifiers begin with @ to refer to whole array • Associative arrays of scalars (hashes) • identifiers begin with % to refer to whole array

  36. Arrays of Scalars • Constant List • (1,3,”Hello”, $value) • Assigned to array • @data = (1,3,”Hello”, $value)

  37. Reference Array Elements as Scalar • @data = (1,3,”abc”,$val); • $data[0] would be 1 • $data[1] would be 3 etc. • Use $ since scalar value - 1 element • Note first element is [0] • Adding elements: $data[4] = 34;

  38. Associative Arrays • Arrays have integers as subscripts • $data[0], $data[1], etc. • Assoc. arrays allow any scalar as subscript • %fruit = (“apple”,3,”pear”,2); • $fruit{‘apple’} has value 3 • $fruit {‘pear’} has value 2 • $fruit{‘orange’}=7; adds new element

  39. Foreach Statement • Easy access of elements foreach $member (@my_array) { print ("$member\n"); }

  40. foreach Examples foreach $elem (@elements) { $elem *= 2; } #!/usr/bin/perl $value="There"; @my_array=(1,3,"Hello",45.6,$value); foreach $member (@my_array) { print ("$member\n"); }

  41. File I/O

  42. Writing to a File open (FILE1, “>myfile.txt”); • Opens myfile.txt for writing. • FILE1 is file handle print FILE1 (“Some text”); close (FILE1); • >>appends

  43. Reading from a File • open (FILE1,”myfile.txt”); • Opened for reading • $text =<FILE1>; • assigns first line to $text • As with writing close is optional

  44. File Test Operators • Test status of file e.g. for existence If (-e “myfile.dat”) { print (“File exists\n”); } else { print (“No such file\n”); } • also r,w,x and z (empty)

  45. Subroutines

  46. Subroutines ...... &subname call ...... sub subname { define statements; }

  47. Local Variables sub subname { local ($x, $y); # or my($x, $y); statements; } • $x and $y are local to subname

  48. Returning Values • $answer = &get_value • Value returned to $answer is last line executed. • Use return to make sure, as in • return ($answer);

  49. Passing Values to a Subroutine $vol = &volume($radius,$length); ...... sub volume { local ($r, $l)=@_; : }

  50. Pattern Matching

More Related