Perl Chapter 6 Functions. Subprograms In Perl, all subprograms are functions – returns 0 or 1 value – although may have “side-effects” optional function.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Introduction to Ruby.
Advertisements

Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
1/12 Steven Leung Very Basic Perl Tricks A Few Ground Rules File I/O and Formatting Operators, Flow Control Statements Regular Expression Subroutines Hash.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
Principles of programming languages 4: Parameter passing, Scope rules Department of Information Science and Engineering Isao Sasano.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
CS 330 Programming Languages 10 / 16 / 2008 Instructor: Michael Eckmann.
COS 381 Day 19. Agenda  Assignment 5 Posted Due April 7  Exam 3 which was originally scheduled for Apr 4 is going to on April 13 XML & Perl (Chap 8-10)
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.
CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections & Chapter 6.
Scripting Languages Perl Chapter #4 Subroutines. Writing your own Functions Functions is a programming language serve tow purposes: –They allow you to.
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.
Names, Bindings, and Scopes
Scope.
Subroutines Just like C, PERL offers the ability to use subroutines for all the same reasons – Code that you will use over and over again – Breaking large.
MT311 Java Application Programming and Programming Languages Li Tak Sing ( 李德成 )
Software II: Principles of Programming Languages Lecture 5 – Names, Bindings, and Scopes.
Chapter Nine: Subprograms Lesson 09. What are they  Modularized code  Might return a value  Functions  Or not  Procedures  Subroutines  In object.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormack 3rd floor 607.
5-1 Chapter 5: Names, Bindings, Type Checking, and Scopes Variables The Concept of Binding Type Checking Strong Typing Type Compatibility Scope and Lifetime.
CS 355 – PROGRAMMING LANGUAGES Dr. X. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Topics Scope Scope and Lifetime Referencing Environments.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
Procedures and Functions Computing Module 1. What is modular programming? Most programs written for companies will have thousands of lines of code. Most.
Variable Scope Storage Class Recursion
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Chapter 5 Names, Bindings, and Scopes. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Chapter 5 Topics Introduction Names Variables The Concept.
ISBN Chapter 5 Names, Bindings, and Scopes.
Introduction A variable can be characterized by a collection of properties, or attributes, the most important of which is type, a fundamental concept in.
ISBN Chapter 5 Names, Bindings, and Scopes.
CS 330 Programming Languages 10 / 07 / 2008 Instructor: Michael Eckmann.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
Python Functions.
Week 6: Functions - Part 2 BJ Furman 01OCT2012. The Plan for Today Comments on midterm exam (next week in lab!) Review of functions Scope of identifiers.
“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
Names, Bindings, and Scope Session 3 Course : T Programming Language Concept Year : February 2011.
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
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.
Structure of Programming Languages Names, Bindings, Type Checking, and Scopes.
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.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
1 PERL Functions. 2 Functions Functions also called subroutines are “free flowing”. The returned value from a function can be interpreted in many different.
CS 330 Programming Languages 10 / 23 / 2007 Instructor: Michael Eckmann.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Operators. Perl has MANY operators. –Covered in Chapter 3 of Camel –perldoc perlop Many operators have numeric and string version –remember Perl will.
APS105 Functions (and Pointers) 1. Modularity –Break a program into manageable parts (modules) –Modules interoperate with each other Benefits of modularity:
Built-In Functions. Notations For each function, I will give its name and prototype. –prototype = number and type of arguments ARRAY means an actual named.
Type Checking, and Scopes
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Names, Bindings, and Scopes
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
User-Defined Functions
C++ for Engineers and Scientists Second Edition
User Defined Functions
Subroutines Web Programming.
Context.
Perl Functions.
Names and Binding In Text: Chapter 5.
Names, Bindings, and Scopes
Subroutines.
Presentation transcript:

Perl Chapter 6 Functions

Subprograms In Perl, all subprograms are functions – returns 0 or 1 value – although may have “side-effects” optional function declaration – heading, no code sub fn_name; function definition – heading, has code – can be ANYWHERE, except inside another function sub fn_name { ….}

C:\>perl sub print_header;print_header();sub print_header{ print “\n Hello\n”; print “\n Hello\n”;}^Z Output:Hello Note: If function declaration used, can call print_header; #with no ()s declaration call definition

Textbook’s Style function definitions first, then program.

Value returning functions Two ways 1.predefined function return 2.returns value of last expression evaluatedsub foo { return (expr);expr;} (1)(2) return function can be called anywhere in function (and in more than one place, but…)

Context of function call context of call (scalar or list) dictates context of evaluation of returned value def: sub =(1,3,5); } call: $scalar = sub1(); #$scalar assigned = sub1(); assigned (1,3,5)

Scope and Lifetime scope – range of statements over which variable is visible (spatial concept) lifetime – begins when created and ends when no longer can be used (temporal concept) global scope – variable visible in whole program file – not good inside a function (name conflicts)

2 kinds of Local variables 1.my – static local just inside function or block 2.local – dynamic local inside function or block and any functions called within block dangerous sub sub1{ my $sum=0;# scope of static local $sum …# is just function sub1 }

Advantage: local variables give slightly faster access than global variables For readability - declare local variables at beginning of function To disallow non-static scoped variables use strict ‘vars’; #also forces all program #variables to be declared my is a function in some situations my = (3,2,7,6);

Parameters actual parameters (arguments) – specified in call to a function formal parameters – variables in function corresponding to actuals pass by value pass by reference (2 ways)

Pass by reference – 1 st way Done through implicit array (use statement use English; in program) At time of call, values of actual parameters are copied At time of return, values copied back.

@list =(1,3,5); fun sub fun{  (6,1,3,5) … } if hash  flattened into array (better to pass by reference 2 nd way) number of actual doesn’t have to match number of formals – too many, ignores – too few, undef

sub addto{ $ARG[0] += $ARG[1]; } $a=5; addto($a, 7); What is $a now? What happens if we try to change $ARG[1]? 12 ignores it, can’t change 7

sub adder{ ++$ARG[0]; ++$ARG[1]; } $ARG[0]=7  8 [1]=1  2 [2]=3 [3]=5 $x now now (2,3,5) sub swap{ ($ARG[1], $ARG[0] = ($ARG[0], $ARG[1]); } swap ($a, $b);

Pass by value values to static locals sub sub1{ my ($x, $y, $z) … } passing hashes by value – make it ONLY parameter sub sub1{ my %my_people … } … sub1(%people);

Passing references as parameters – 2 nd way pass references to actual parameters – ref to array  single scalar assigned – array  copies ALL elements sub do_array{ my $ref_list = $ARG[0]; … } … do_array #same with a hash \%table

Apply function to list of parameters sub do_list{ … } ($count, ARRAY LAST!

indirect calls if you have one of five different functions to be called depending on a string value of scalar variable – simulated switch or – construct hash of string key => address of function

predefined functions abs, chr, exit, exp, ord, log, rand, sqrt warn instead of die ….

sort function (again) additional parameter specifies comparison operator #default was ascending cmp on strings for numbers, use as comparison operator array of numbers in ascending = sort {$a #book typo array of numbers in descending = sort{$b array of strings in descending = sort{$b cmp

Handout A subroutine defined or declared without parameter list can be called without any restrictions on the number or type of parameters passed A subroutine defined with a parameter list MUST be called with exactly the parameters specified or compilation error results

Sample parameter lists () zero parameters required or accepted ($) 1 scalar parameter required ($; 1 scalar parameter required, 2 nd parameter optional, but must be array (reference) First 3 scalar, remaining actual put in ending put in ending array array reference, hash reference, scalar, 2 optional scalars

sub subp my ($arrayRef1, $size, $arrayRef2, $hashRef, } %table, $tableSize);

Future Skip chapter 7 for now (Pattern Matching) Did 8 Go to 9 on Monday on CGI programming w/ Perl