660 likes | 882 Views
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
E N D
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 • Pattern Matching • Subroutines
Topics /contd • Accessing UNIX • Command Line • Common Errors
Where to Find Perl • Usually at /usr/bin/perl • or /usr/local/bin
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
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
A Simple Perl Program #!/usr/bin/perl # this is a simple perl program $name= “Hello”; print (“$name\n”); Entered in file - first.pl
Running Perl Programs • Type perl followed by filename • $ perl first.pl
What Happens? • Syntax Checked • Executed • All with one command
Perl Errors • When Perl comes across a syntax error - Error Message returned • Will not execute if there are syntax errors.
Scalar Variables • always start with $ • Not declared • No naming distinction between numeric and string • $x = 47; • $x = “A String.”; • Naming rules
Input • To read in from keyboard • $line = <STDIN>;
The Chop Function • $line = <STDIN>; • $line includes newline at end of string • Use chop function to remove it. chop ($line);
Doing Sums • Arithmetic operators • + add • - subtract • * multiply • / divide • $x = $y / $z;
Strings and Things • Print function $result = 345; print (“The result is $result\n”); print (“The result is ”,$result, ”\n”); The result is 345
Escape Characters • \n newline • \t tab • \L all following letters lowercase • \$ to print the “$” • print (“The value of \$result is $result\n”);
Branching - If Statement if ($x == $y) { print (“The numbers are equal”); } Print (“Done.\n”); • If expression true evaluate code in { }
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.
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
Comparison Operators • Arithmetic == > < >= <= != • String eq gt lt ge le ne • NB Don’t mix them up or confuse with assignment (=)
Logical Operators • And && • Or || • Not ! ($x < 20 && $x > 13) • True if x is between 13 and 20. • ($ans eq “Y” || $ans eq “y”)
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.
Two Common Errors print("Exit program? Enter yes or no -"); $response =<STDIN>; if ($response = "yes") { die ("Quit on user request"); } print ("Program continuing...\n");
Looping - While $count=0; while ($count < 5) { $count = $count+1; print ("count is $count\n"); } • While expression is true execute code in { }
Incrementing • $count = $count + 1; • $count +=1; • $count++; • ++$count; • All increment $count
Auto - Increment • Pre and post • $y = ++$x; increment then assign • $y = $x++; assign then increment • Can be confusing
Until Loop • While - loops while true • Until - loops until true $x = <STDIN>; chop ($x); until ($x == 24) { $x=<STDIN>; chop $x; }
For Loop for ($count=1; $count<=5;$count++) { print ("count is $count\n"); } • More readable than while • avoids problem with missing counter
Perl Operators • . Concatenation • x Repeat • http://www.codebits.com/p5be/ch04.cfm
Perl Functions • Array: • chop chomp • join split splice • pop push • shift unshift • reverse sort • http://www.codebits.com/p5be/xp0c.cfm
Accessing the UNIX System • $return = `unix_command`; • ` is backquote • Example • $files= `ls`; • $files contains list of files
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
Arrays of Scalars • Constant List • (1,3,”Hello”, $value) • Assigned to array • @data = (1,3,”Hello”, $value)
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;
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
Foreach Statement • Easy access of elements foreach $member (@my_array) { print ("$member\n"); }
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"); }
Writing to a File open (FILE1, “>myfile.txt”); • Opens myfile.txt for writing. • FILE1 is file handle print FILE1 (“Some text”); close (FILE1); • >>appends
Reading from a File • open (FILE1,”myfile.txt”); • Opened for reading • $text =<FILE1>; • assigns first line to $text • As with writing close is optional
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)
Subroutines ...... &subname call ...... sub subname { define statements; }
Local Variables sub subname { local ($x, $y); # or my($x, $y); statements; } • $x and $y are local to subname
Returning Values • $answer = &get_value • Value returned to $answer is last line executed. • Use return to make sure, as in • return ($answer);
Passing Values to a Subroutine $vol = &volume($radius,$length); ...... sub volume { local ($r, $l)=@_; : }