Perl FunctionsLearning Objectives:To learnhow to createfunctions in a Perl'sprogram &howtocall themTo learn howto pass[structured] arguments一intofunctions&return value fromafunctionTo understand the scope of a Perl's program3
Perl Functions Learning Objectives: 1. To learn how to create functions in a Perl’s program & how to call them 2. To learn how to pass [structured] arguments into functions & return value from a function 3. To understand the scope of a Perl’s program
COMP111Lecture18/Slide2Defining a Function (1)A user-defined function or subroutine is defined in Perlas follows:sub subnamestatementl;statement2;statement3;Simple Examplesub hello(print "hello world!\n";1
COMP111 Lecture 18 / Slide 2 ▪ A user-defined function or subroutine is defined in Perl as follows: sub subname{ statement1; statement2; statement3; } ▪ Simple Example: sub hello{ print "hello world!\n"; } Defining a Function (1)
COMP111Lecture18/Slide3DefiningaFunction(2)Subroutine definitions can be anywhere in your programtext (they are skipped on execution)Within the subroutine body, you may use any variablefrom the main program (variables in Perl are global bydefault).#!/usr/local/bin/perl5-wsuser = "horner";hello();print "goodbye suser!ln";sub helloprint "hello suser!n";
COMP111 Lecture 18 / Slide 3 Defining a Function (2) ▪ Subroutine definitions can be anywhere in your program text (they are skipped on execution) ▪ Within the subroutine body, you may use any variable from the main program (variables in Perl are global by default). #!/usr/local/bin/perl5 -w $user = "horner"; hello(); print "goodbye $user!\n"; sub hello{ print "hello $user!\n"; }
COMP111Lecture18/Slide4Global VariableYou can also use variables from the subroutine back inthe main program (it is the same global variable):s cat suml#!/usr/local/bin/perl5-wsa = 1;sb=2;ssum = 0;sum a and b();print "sum of sa plus sb: ssumln";sub sum a and btssum = $a + sb;福$ sumlsum of 1 plus 2: 3s
COMP111 Lecture 18 / Slide 4 Global Variable ▪ You can also use variables from the subroutine back in the main program (it is the same global variable): $ cat sum1 #!/usr/local/bin/perl5 -w $a = 1; $b = 2; $sum = 0; sum_a_and_b(); print "sum of $a plus $b: $sum\n"; sub sum_a_and_b{ $sum = $a + $b; } $ sum1 sum of 1 plus 2: 3 $
COMP111Lecture18/Slide5Sorting Question RevisitedConsider a %students,$ID!‘CGA! from last lecturePrint out the students' ID's and CGA's in order ofstudent CGAModify sort function by order of student's CGAforeach $ID (sort by CGA keys(%students)Subby CGA(Sstudents(sa)('CGA)<->sstudents(sb)(CGA)I(sacmpsb);
COMP111 Lecture 18 / Slide 5 Sorting Question Revisited ▪ Consider a %students{$ID}{‘CGA”} from last lecture ▪ Print out the students’ ID’s and CGA’s in order of student CGA. ▪ Modify sort function by order of student’s CGA foreach $ID ( sort by_CGA keys(%students) ) { . . } sub by_CGA { ($students{$a}{‘CGA'} <=> $students{$b}{‘CGA'}) || ($a cmp $b); }