Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, 88-91 Programming Perl 3rd edition pages 80-83,

Slides:



Advertisements
Similar presentations
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Advertisements

Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
The Linux Operating System Lecture 6: Perl for the Systems Administrator Tonga Institute of Higher Education.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
CSET4100 – Fall 2009 Perl Introduction Scalar Data, Operators & Control Blocks Acknowledgements: Slides adapted from NYU Computer Science course on UNIX.
COS 381 Day 19. Agenda Questions?? Resources Source Code Available for examples in Text Book in Blackboard
Scripting Languages Chapter 6 I/O Basics. Input from STDIN We’ve been doing so with $line = chomp($line); Same as chomp($line= ); line input op gives.
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
Perl Functions Software Tools. Slide 2 Defining a Function l A user-defined function or subroutine is defined in Perl as follows: sub subname{ statement1;
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.
Sorting. Simple Sorting As you are probably aware, there are many different sorting algorithms: selection sort, insertion sort, bubble sort, heap sort,
Scripting Languages Perl Chapter #4 Subroutines. Writing your own Functions Functions is a programming language serve tow purposes: –They allow you to.
Guide To UNIX Using Linux Third Edition
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.
Subroutines. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc We’ll just say Subroutines. –“Functions” generally means built-in.
Topic 5: Hashes CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 5, pages Programming Perl 3rd edition pages 76-78, , ,
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Control Structures. Important Semantic Difference In all of these loops we are going to discuss, the braces are ALWAYS REQUIRED. Even if your loop/block.
Topic 1: Welcome CSE2395/CSE3395 Perl Programming.
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.
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
Topic 11: Object-oriented Perl CSE3395 Perl Programming Camel3 chapter 12, pages perlobj, perltoot, perlbot, perlmod manpages.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CS 330 Programming Languages 10 / 07 / 2008 Instructor: Michael Eckmann.
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.
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.
Introduction to Perl Part III By: Bridget Thomson McInnes 6 Feburary 2004.
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.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
Computer Programming for Biologists Class 3 Nov 13 th, 2014 Karsten Hokamp
Introduction to Perl “Practical Extraction and Report Language” “Pathologically Eclectic Rubbish Lister”
JavaScript, Fourth Edition
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Chapter 11: Perl Scripting Off Larry’s Wall. In this chapter … Background Terminology Syntax Variables Control Structures File Manipulation Regular Expressions.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004.
CPTG286K Programming - Perl Chapter 5 & 6: Hashes & Basic I/O.
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.
A Few More Functions. One more quoting operator qw// Takes a space separated sequence of words, and returns a list of single-quoted words. –no interpolation.
Topic 2: Working with scalars CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 2, pages 19-38, Programming Perl 3rd edition chapter.
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
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.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
Topic 3: Lists and arrays CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 3, pages 40-55, 86-91, Programming Perl 3rd edition.
2.1 Scalar data - revision numeric e-14 ( = 6.35 × )‏ operators: + (addition) - (subtraction) * (multiplication) / (division)
Computer Programming for Biologists Class 4 Nov 14 th, 2014 Karsten Hokamp
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
2000 Copyrights, Danielle S. Lahmani Foreach example = ( 3, 5, 7, 9) foreach $one ) { $one*=3; } is now (9,15,21,27)
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
Perl Subroutines User Input Perl on linux Forks and Pipes.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Introduction to Programming the WWW I CMSC Winter 2004 Lecture 8.
String and Lists Dr. José M. Reyes Álamo.
Chapter 9: Value-Returning Functions
Chapter 5 - Control Structures: Part 2
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
LING/C SC/PSYC 438/538 Lecture 4 Sandiway Fong.
Perl Variables: Array Web Programming.
Context.
String and Lists Dr. José M. Reyes Álamo.
Subroutines.
Presentation transcript:

Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83, , 659, perlsub manpage

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 2 In this topic  Command-line arguments  The diamond operator <>  Subroutines ► declaring ► calling ► returning from  Local variables  Perl debugger  Command-line arguments  The diamond operator <>  Subroutines ► declaring ► calling ► returning from  Local variables  Perl debugger

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 3 Command-line arguments  Words on command line after script name are considered command-line arguments ► perl -w mystery Agatha Arthur "Erle Stanley" –three command-line arguments: “Agatha”, “Arthur”, “Erle Stanley” –broken up into space-separated words by shell –except where quoted or escaped  Command-line arguments are available to Perl array ► first argument is in $ARGV[0] –not like C, where argv[0] is program name –Perl script name can be found in special variable $0 (zero) ► unlike C, no need for argc parameter ’s size is known ► if no command-line is empty  Words on command line after script name are considered command-line arguments ► perl -w mystery Agatha Arthur "Erle Stanley" –three command-line arguments: “Agatha”, “Arthur”, “Erle Stanley” –broken up into space-separated words by shell –except where quoted or escaped  Command-line arguments are available to Perl array ► first argument is in $ARGV[0] –not like C, where argv[0] is program name –Perl script name can be found in special variable $0 (zero) ► unlike C, no need for argc parameter ’s size is known ► if no command-line is empty Llama3 pages 90-91; Camel3 page 659; perlvar manpage

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 4 Timeout #!/usr/bin/perl -w print "Program name is: $0\n"; print "Parameters are:\n"; for ($i = 0; $i <= $#ARGV; $i++) { print " $i: $ARGV[$i]\n"; } #!/usr/bin/perl -w print "Program name is: $0\n"; print "Parameters are:\n"; for ($i = 0; $i <= $#ARGV; $i++) { print " $i: $ARGV[$i]\n"; }

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 5 Filters  Many Unix programs can act as filters ► if files named on command line, program processes files in order –sort file1 file3 file4 # Sort all together ► if no files named on command line, program processes standard input –cat file1 file3 file4 | sort # Same ► filename “ - ” also means standard input –sort filling | cat slice1 - slice2 # Sandwich  Perl makes this easy with <> (“diamond”) operator ► <> reads lines of input, like  Many Unix programs can act as filters ► if files named on command line, program processes files in order –sort file1 file3 file4 # Sort all together ► if no files named on command line, program processes standard input –cat file1 file3 file4 | sort # Same ► filename “ - ” also means standard input –sort filling | cat slice1 - slice2 # Sandwich  Perl makes this easy with <> (“diamond”) operator ► <> reads lines of input, like Llama3 pages 88-90; Camel3 pages 80-83

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 6 <> (diamond) operator  If files named as command-line arguments ► <> returns lines from file named in $ARGV[0] ► then returns lines from file named in $ARGV[1] ► until all lines in all files read, then returns undef ► no need to open or close files or detect EOF between files  If no command-line arguments ► <> behaves the same as  If files named as command-line arguments ► <> returns lines from file named in $ARGV[0] ► then returns lines from file named in $ARGV[1] ► until all lines in all files read, then returns undef ► no need to open or close files or detect EOF between files  If no command-line arguments ► <> behaves the same as

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 7 Timeout #!/usr/bin/perl -w # Unix cat program while (<>) { print; } #!/usr/bin/perl -w # Unix cat program while (<>) { print; }

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 8 Timeout #!/usr/bin/perl -w # Even shorter Unix cat program print while (<>); # That’s it. #!/usr/bin/perl -w # Even shorter Unix cat program print while (<>); # That’s it.

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 9 Subroutines  In Perl, functions are called subroutines ► declared with sub keyword  In Perl, functions are called subroutines ► declared with sub keyword sub name { # Body goes here } sub keyword declares the subroutine put name of subroutine here Llama3 page 57; Camel3 pages ; perlsyn manpage

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 10 Calling subroutines  Subroutines officially begin with & character ► $thing is is array, &thing is subroutine  In practice, & is almost never needed ► not used when defining with sub keyword ► not needed when calling because parentheses identify it as a subroutine ► &weekday(2004,6,1) or weekday(2004,6,1)  Subroutines officially begin with & character ► $thing is is array, &thing is subroutine  In practice, & is almost never needed ► not used when defining with sub keyword ► not needed when calling because parentheses identify it as a subroutine ► &weekday(2004,6,1) or weekday(2004,6,1) Llama3 pages57-58, 70-71; Camel3 page 218

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 11 Calling subroutines  Caller names arguments as list after subroutine name ► $newyearsday = weekday($year, 1, 1); ► as with built-in functions, can omit parentheses if subroutine is predeclared  Argument list is evaluated and placed in special local array ► argument is unrelated to default argument $_  Subroutine can access members to get parameter values ► sub weekday { ($y, $m, $d) } ► sub weekday { $y = $_[0];... }  Caller names arguments as list after subroutine name ► $newyearsday = weekday($year, 1, 1); ► as with built-in functions, can omit parentheses if subroutine is predeclared  Argument list is evaluated and placed in special local array ► argument is unrelated to default argument $_  Subroutine can access members to get parameter values ► sub weekday { ($y, $m, $d) } ► sub weekday { $y = $_[0];... } Llama3 pages 60-62; Camel3 pages

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 12 Subroutine return  Return value of a subroutine is the last expression evaluated ► sub pi { ; }  Can use return keyword to return sooner ► sub absx { if ($x >= 0) { return $x; } else { return -$x; } }  Return value can be scalar or list ► return (1, 2, 3); ► return value is evaluated in scalar or list context depending on context subroutine was called in ► can use wantarray function to determine context  Return value of a subroutine is the last expression evaluated ► sub pi { ; }  Can use return keyword to return sooner ► sub absx { if ($x >= 0) { return $x; } else { return -$x; } }  Return value can be scalar or list ► return (1, 2, 3); ► return value is evaluated in scalar or list context depending on context subroutine was called in ► can use wantarray function to determine context Llama3 pages 58-60, 69-70; Camel3 pages 219,228

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 13 Timeout # Compute the hypotenuse of a triangle # Declare the subroutine sub hypotenuse { # Return root of sum of squares. sqrt($_[0] * $_[0] + $_[1] * $_[1]); } # Read two numbers. print "Enter first number: "; chomp ($a = ); print "Enter second number: "; chomp ($b = ); print "Hypotenuse is ", hypotenuse($a, $b), "\n"; # Compute the hypotenuse of a triangle # Declare the subroutine sub hypotenuse { # Return root of sum of squares. sqrt($_[0] * $_[0] + $_[1] * $_[1]); } # Read two numbers. print "Enter first number: "; chomp ($a = ); print "Enter second number: "; chomp ($b = ); print "Hypotenuse is ", hypotenuse($a, $b), "\n";

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 14 Timeout # Compute the hypotenuse of a triangle # Declare the subroutine sub hypotenuse { # Give the parameters meaningful names. ($x, $y) # This has a slight bug. sqrt($x * $x + $y * $y); } # Read two numbers. print "Enter first number: "; chomp ($a = ); print "Enter second number: "; chomp ($b = ); print "Hypotenuse is ", hypotenuse($a, $b), "\n"; # Compute the hypotenuse of a triangle # Declare the subroutine sub hypotenuse { # Give the parameters meaningful names. ($x, $y) # This has a slight bug. sqrt($x * $x + $y * $y); } # Read two numbers. print "Enter first number: "; chomp ($a = ); print "Enter second number: "; chomp ($b = ); print "Hypotenuse is ", hypotenuse($a, $b), "\n";

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 15 Local variables with my  By default, all variables are global  Variables can be declared local with my function ► my $x;  Variables declared with my are accessible only within enclosing block (usually until end of loop or subroutine) ► “lexical scoping”, like local variables in C ► Perl also has “dynamic scoping” like shell, uses local function  Can localize more than one variable at once ► my ($x, # Need brackets  Can localize and initialize in one step ► my ($x, $y)  By default, all variables are global  Variables can be declared local with my function ► my $x;  Variables declared with my are accessible only within enclosing block (usually until end of loop or subroutine) ► “lexical scoping”, like local variables in C ► Perl also has “dynamic scoping” like shell, uses local function  Can localize more than one variable at once ► my ($x, # Need brackets  Can localize and initialize in one step ► my ($x, $y) Llama3 pages 62-64; Camel3 pages ; perlfunc manpage

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 16 Timeout # Sum a variable-length list of numbers. # Read some numbers while (<>) { chomp; $_; } print "Sum is ", sum "\n"; sub sum { my $sum = 0; # Iterate over parameter foreach my $num # With local iterator $num. { $sum += $num; # Add this element to running total. } return $sum; } # Sum a variable-length list of numbers. # Read some numbers while (<>) { chomp; $_; } print "Sum is ", sum "\n"; sub sum { my $sum = 0; # Iterate over parameter foreach my $num # With local iterator $num. { $sum += $num; # Add this element to running total. } return $sum; }

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 17 Passing array parameters  Arrays are flattened into lists before being put into parameter ► func($x, –$_[0] = x; $_[1] = y; ► sizes of arrays are lost in flattening ► array must be reconstructed by subroutine –e.g., my ($x,  If passing one array to a subroutine, make it the last argument ► func($x, # Not $y) –elements $_[2] to end must be  Don’t pass more than one array to a function won’t work because of list flattening –diff won’t know ends and begins ► can be solved using references (Topic 11)  Arrays are flattened into lists before being put into parameter ► func($x, –$_[0] = x; $_[1] = y; ► sizes of arrays are lost in flattening ► array must be reconstructed by subroutine –e.g., my ($x,  If passing one array to a subroutine, make it the last argument ► func($x, # Not $y) –elements $_[2] to end must be  Don’t pass more than one array to a function won’t work because of list flattening –diff won’t know ends and begins ► can be solved using references (Topic 11) Camel3 pages 221,

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 18 Subroutines in built-in functions  Anonymous subroutine bodies (“closures”) are used by some built-in Perl functions  map { code ► “modify” operation: create a new list with code applied to each element  grep { code ► “filter” operation: create a new list from only the elements where code is true  sort { code ► custom sorting: use code to compare two elements of list to determine their sorted order  Can also use closures in user-defined functions ► requires use of references (Topic 11)  Anonymous subroutine bodies (“closures”) are used by some built-in Perl functions  map { code ► “modify” operation: create a new list with code applied to each element  grep { code ► “filter” operation: create a new list from only the elements where code is true  sort { code ► custom sorting: use code to compare two elements of list to determine their sorted order  Can also use closures in user-defined functions ► requires use of references (Topic 11) Llama3 pages , ; Camel3 pages 730, ; perlfunc manpage

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 19 Timeout # Censor: remove four-letter words from input. while (<>) { # Break line into words. # split function explained in topic = split /\s+/, $_; # Put only words which match the expression # (length not equal to 4) # $_ is each element in turn # (a bit like foreach loop = grep { length $_ != 4 print } # Censor: remove four-letter words from input. while (<>) { # Break line into words. # split function explained in topic = split /\s+/, $_; # Put only words which match the expression # (length not equal to 4) # $_ is each element in turn # (a bit like foreach loop = grep { length $_ != 4 print }

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 20 Timeout # Sorting a list = (1, 64, 8, 2, 16, 128, 4, 32); # sort function normally sorts items # alphabetically as = print "As # Sorting comparison routine (automatically given two # parameters $a and $b) can specify how items collate. # -1: $a precedes $b; +1: $a follows $b; 0: = sort { if ($a < $b) { return -1; } elsif ($a > $b) { return 1; } else { return 0; } print "As # Sorting a list = (1, 64, 8, 2, 16, 128, 4, 32); # sort function normally sorts items # alphabetically as = print "As # Sorting comparison routine (automatically given two # parameters $a and $b) can specify how items collate. # -1: $a precedes $b; +1: $a follows $b; 0: = sort { if ($a < $b) { return -1; } elsif ($a > $b) { return 1; } else { return 0; } print "As

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 21 Timeout # Sorting a list = (1, 64, 8, 2, 16, 128, 4, 32); # sort function normally sorts items # alphabetically as = print "As # Numerical sorting is so common there is # shorthand for it using the "spaceship" # operator which returns -1, 0 or = sort { $a $b print "As # Sorting a list = (1, 64, 8, 2, 16, 128, 4, 32); # sort function normally sorts items # alphabetically as = print "As # Numerical sorting is so common there is # shorthand for it using the "spaceship" # operator which returns -1, 0 or = sort { $a $b print "As

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 22 Perl debugger  Perl has a built-in source-level debugger ► perl -d script...arguments...  Most useful commands ► r (run) ► n (next line, skip through nested subroutines) ► s (step, stop at subroutine calls) ► b line (break when line reached) ► c (continue running) ► p expr (print expression) ► x list (examine list expression) ► l (list code) ► q (quit debugger)  Perl has a built-in source-level debugger ► perl -d script...arguments...  Most useful commands ► r (run) ► n (next line, skip through nested subroutines) ► s (step, stop at subroutine calls) ► b line (break when line reached) ► c (continue running) ► p expr (print expression) ► x list (examine list expression) ► l (list code) ► q (quit debugger) Llama3 page 294; Camel3 pages ; perldebug manpage

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 23 Covered in this topic  Command-line arguments array  The diamond operator <> ► related  Subroutines ► declaring with sub ► calling ► returning from  Local variables ► my function  Built-in functions using closures ► map, grep, sort  Perl debugger  Command-line arguments array  The diamond operator <> ► related  Subroutines ► declaring with sub ► calling ► returning from  Local variables ► my function  Built-in functions using closures ► map, grep, sort  Perl debugger

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 24 Going further  Prototypes ► making user-defined subroutines behave more like builtins ► Camel3 pages  Code generation ► building Perl code on the fly with eval ► Camel3 pages  Built-in functions ► a myriad of standard subroutines provided by Perl ► Camel3 pages  BEGIN and END ► special functions that run before or after other code (see also awk ) ► Camel3 pages  Prototypes ► making user-defined subroutines behave more like builtins ► Camel3 pages  Code generation ► building Perl code on the fly with eval ► Camel3 pages  Built-in functions ► a myriad of standard subroutines provided by Perl ► Camel3 pages  BEGIN and END ► special functions that run before or after other code (see also awk ) ► Camel3 pages

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 25 Next topic  Hashes ► aka associative arrays ► arrays indexed by strings, not numbers  Hash variables and functions  Hashes ► aka associative arrays ► arrays indexed by strings, not numbers  Hash variables and functions Llama3 chapter 5, pages Camel3 pages 76-78, , , perldata manpage