Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year 2014-2015.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Introduction to C Programming
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.
C Language.
Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
VBA Modules, Functions, Variables, and Constants
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
CS 330 Programming Languages 09 / 30 / 2008 Instructor: Michael Eckmann.
Scripting Languages Perl Chapter #4 Subroutines. Writing your own Functions Functions is a programming language serve tow purposes: –They allow you to.
Adapted from Dr. Craig Chase, The University of Texas at Austin.
Introduction to C Programming
Introduction to Methods
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Chapter 6: Function. Scope of Variable A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
Using Data Active Server Pages Objectives In this chapter, you will: Learn about variables and constants Explore application and session variables Learn.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Lists in Python.
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CS 330 Programming Languages 10 / 07 / 2008 Instructor: Michael Eckmann.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
CPS120: Introduction to Computer Science Decision Making in Programs.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Variables, Functions and Events (there is an audio component to this eLesson) © Dr.
CPS120: Introduction to Computer Science Functions.
Introduction to Perl Yupu Liang cbio at MSKCC
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
David Stotts Computer Science Department UNC Chapel Hill.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Lecture 5 1.What is a variable 2.What types of information are stored in a variable 3.Getting user input from the keyboard 1.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Perl Chapter 6 Functions. Subprograms In Perl, all subprograms are functions – returns 0 or 1 value – although may have “side-effects” optional function.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
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.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Perl Day 5. Arrays vs Hash Arrays are one way to store multiple things in a variable. Hashes are another. Arrays are one way to store multiple things.
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
Controlling Computers with Programs When you create a computer program you are creating a set of instructions that tell the computer exactly and completely.
Controlling Program Flow with Decision Structures.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
Embedding Assembly Code in C Programs תרגול 7 שילוב קוד אסמבלי בקוד C.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Creating FunctionstMyn1 Creating Functions Function can be divided into two groups: –Internal (built in) functions –User-defined functions.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Information and Computer Sciences University of Hawaii, Manoa
User-Written Functions
Chapter 6 JavaScript: Introduction to Scripting
Variables, Expressions, and IO
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
Chapter 4 void Functions
CISC101 Reminders Assignment 3 due today.
Corresponds with Chapter 5
Presentation transcript:

Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year

Functions and Perl Almost every high-level programming language supports functions and Perl is no exception. Simply put, a function is a block of code that can be called by name to perform some task, then return to the calling program. Functions can usually accept parameters and return values. You’ve seen a lot of functions so far: print, reverse, sort, open and so on are all built-in functions Perl calls user-defined functions “subroutines” or “subs”

Creating a subroutine To create a Perl subroutine, you use the keyword sub followed by the subroutine name and the code for that subroutine in curly braces: sub sub_name { statements… } Subroutine names do not have any specific character first, and naming rules are the same as other variables in Perl

Running a subroutine To run a subroutine in Perl, you can use one of two syntaxes: subname(); or &subname(); The ampersand is optional in almost all cases, as is most commonly left off. If you are passing parameters to the subroutine, they would be enclosed in the parentheses. &subname($argument1, $argument2); Subroutines can call other subroutines, or themselves recursively

Returning values Many subroutines will return a value when the subroutine code has been executed. This value is usually assigned to a variable or used in a statement like print. For example: sub twoplustwo { 2+2;} $num1=8+twoplustwo; In this case, $num1 will have the value of 12. In this case there is no return statement in the subroutine as with other languages. The last expression in the code is returned by the sub.

Using return You can use a return statement if you want to specify what to return from a subroutine or want to have the option of terminating the sub early: sub oddeven { return(0) if ($num%2 == 0); statements…} In this case, $num will have been defined outside the subroutine. If the mod 2 of that number is 0, the returned number will be zero and the sub terminates at this point. Otherwise, the program continues executing the statements.

Returning variables You can return any variable from a subroutine, including hashes and arrays: sub somesub { statements… statements…} In this code, an array is returned from the sub and reversed in the body of the Perl script, then stored in a new array variable

Exercise Write two subroutines. Both use a variable defined in the body of the program. The first sub multiplies the variable by ten, while the second sub divides the number by two. Prompt the user for the number, and then call both subs and display the results from the Perl script (not the subs).

Arguments The code we wrote so far depends on a variable being defined outside a subroutine, and that’s not good because this reduces code reuse. Ideally, subroutines should be stand-alone and portable. To pass data to a subroutine as part of the subroutine call is to use arguments. You’ve seen arguments passed to functions with several built-in functions, such as sort. To pass arguments to a subroutine, you specify them as part of the subroutine call.

Specifying arguments Arguments for a subroutine can be specified in two ways, either with or without parentheses (most Perl functions don’t care about parentheses as you have seen already in this course): sub(args…); sub args…; You can only leave off the parentheses if the subroutine has been defined earlier in the script that the subroutine call. This is a common error for programmers who define subroutines at the end of their code.

Multiple arguments The args list can be composed of many arguments, all separated by commas: sub1 arg1, arg2, arg3; There is no limit to the number of arguments that can be passed to a subroutine, and they can be of any valid type or size. You can mix argument types in the list passed to the subroutine: sub1

variable Inside the subroutine, Perl uses the argument to hold all the arguments. You can in your subroutines: sub showarg { print join(“ showarg (“This”,“is”,“a”,“test”) ; This program passes the four strings to showarg, which uses the join to paste them together with spaces between each one. The print displays the result. variable is not related to the $_ variable

Accessing each argument Inside a subroutine, each argument is accessed as a part of array using subscripts, as with any array. The first argument will be element $_[0], the second array element $_[1], and so on. You can use loops to access each argument using the array element name

Using names for arguments Inside a subroutine, using $_[x] can be awkward and counter-intuitive. Perl allows you to name arguments being passed into the subroutine, just as with other language function arguments, but you have to do it by assigning array elements at the top of the subroutine code: sub foo1{ ($var1, statements…} This will assign the first argument to $var1, and the second to $var2, and so on if more are named

Exercise Write a subroutine that expects three numbers passed as arguments, and multiply the three together, returning the result from the subroutine. Call the subroutines from inside a Perl script that asks the user for all three numbers. Use names for each argument inside the subroutine itself.

Passing an array or hash Passing an array or hash to a subroutine is done in the same way as passing scalars: sub revarray { return This will pass the to the subroutine revarray, reverse it, and store the result passed back from the subroutine The entire array is read in to the subroutine

Passing multiple arrays or hashes, Part 1 You might think you could pass more than one array or hash in the same manner: sub printarrays however this will not work will hold the two arrays together and there is no way to break them into two separate arrays in the subroutine. There is no indication where one array ends and the next starts. In this would have the contents is empty.

Passing multiple arrays or hashes, Part 2 There is no easy way to solve this problem of passing arrays directly. However, they can be passed through a reference. You can pass one array and a mix of scalars without problem as long as the array or hash is the last assigned element. The scalars will be properly assigned from array and everything else goes in the array: sub passarrays { ($x1, $x2, $x3, statements…;}

Exercise Write a program that contains a subroutine that accepts one letter and an array of letters. Prompt the user in the main part of the Perl script for the letter, then for five strings to be sent as an array. Inside the script, combine the five elements in the array into a scalar string, using the letter as a joining character, and pass the result back to the script. Display the resulting string.

Scope If you have programmed in any other language that supports functions, you have seen scope. Scope refers to the block of code where a variable has meaning. If you define variables inside a Perl script they are available to any subroutines inside that script. Variables created inside a subroutine are available outside the subroutine, as well (which is not how most programming languages behave). This is an important difference in language! In this case, the variables have scope in the entire program.

Keeping it private with “my” To help code reuse and portability, you want to be able to define variables inside a subroutine that have no meaning outside the subroutine. This prevents conflicts with other script variables when you move the subroutine to new programs. To define a local variable, you use the my operator: my $var1; Any variable defined with the word my is considered private to the block of code it is defined in. That is where the variable has scope.

Private variables Any variable defined with the keyword my to make it private is released as soon as the code block in which it was defined is terminated You can have private and global variables with the same name, and they are treated differently by the compiler: $num1=6; sub something { my $num1; # different variable statements…} Both $num1s are treated as different in this case

Using strict Perl has a keyword called strict. When used in a program, it tells the interpreter to use much more care when evaluating statements and to display warnings and error messages for everything it finds questionable (usually Perl will let you get away with quite a bit before complaining about something). Using strict is a good way to enhance your programming abilities. To do this, simply put: use strict; at the top of your code.

References If you have programmed in C, C++, or other high level languages, you may be familiar with pointers, which are the same as Perl’s references. If you have not seen these capabilities before, the learning curve is a little steep. To help show the abilities of references we have used very simple exercises throughout. This should show the basics of the subject without overwhelming you.

References A variable that points to the memory address of another variable. Perl has pointers too, but they are called references. References do not hold a variable value, but hold the memory address of another variable. For example, if you have a variable called $num1, you could have a reference called $refnum1 which holds the memory address when $num1 has its data stored.

What is a reference Every variable in Perl has a value assigned in memory. Any value assigned to that variable is contained in that memory. For example, the statement: $num1=10; will have a memory location assigned with the name $num1, and a value of 10 is stored in that memory location. A reference is another variable, and has an assigned memory location, but holds the address of the $num1 memory location instead of a value.

Why use references Why bother using a reference to a memory location with a value in it? There are many reasons when you get into complex coding, but the simplest reason is it allows you to change the variable the reference points to (and hence the value it points to in that variable’s memory location). This is very handy in some programs, as you will see. References are especially handy when dealing with arrays and lists

Creating a reference References are created exactly the same way as other variables, and have no special naming convention. To assign a value to the reference, you use the backslash: $refnum1=\$num1; This will create a reference variable called $refnum1which will hold the memory address of the variable $num1. Creating a reference to a variable doesn’t affect the variable in any way.

Dereferencing To use the value a reference is pointing to, you have to tell the interpreter that you don’t want to know the memory address it holds, but the value inside the memory address it points to. This is done with the dereferencing operator. For example: print $refnum1; will print the memory address $refnum1 holds, but print $$refnum1; will print the value in the memory address of $num1 (if that’s what it points to).

Using references to change values You can use dereferencing to change the value of a variable the reference points to. This is done in the same way as looking up the value: $$refnum1=15; This command will change the value in the memory location $refnum1 points to and set the value of 15 there. You have to use two $ signs here: if you had written $refnum1=15; you would be setting the value 15 into the memory location of $refnum1, not the variable it points to.

Exercise Write a program that create a variable with a user-supplied value. Create a reference to that variable. Display the memory address of the reference and the value stored in the dereferenced variable.

Using reference values When a reference has been given a value (a memory location of a variable), the reference can be used with other variables and references. For example: $num1=10; $refnum1=\$num1; $refnum2=$refnum1; print $$refnum2; will have $refnum1 point to $num1. $refnum2 then is set to the same value, so the last line shows the dereferenced value of $refnum2, or 10.

Exercise Write a program that sets up five scalars filled with numbers supplied by the user. Then, set up a reference variable that points to the first scalar. Display the dereferenced values of that variable.

References to arrays You can set up a reference to an array in the same way as a reference to a scalar. Since the reference holds a memory address, it is a scalar itself and defined with a “2”, “3”); The variable $refarray1 will have the memory address of the first element of the It does not point to the entire array, just the start of the memory

Dereferencing array references To dereference array references, you can reference any element in the array pointed to with the usual element subscript: $$refarray1[2]; This shows the value of the third element in whatever $refarray points to. If you want to see the whole array, You can see a range of elements, shows the first four element in the array.

Exercise Write a program that prompts the user for five strings, and save them as elements in an array. Then, set a reference to that array. Use a loop/subroutine to show each of the elements in that array using the reference, one element at a time.

References to hashes References to hashes are set up the same way as arrays: $refhash1=\%hash1; You access single elements in the hash through the hash key, and get the value associated with that key back: $$refhash1{$key}; To see the whole hash the reference points to, use: %$refhash1;

Exercise Create a hash and a reference to that hash. You can either prompt the user for hash keys and values, or simply hardcode them to save time. Use a loop to display all the values associated with each hash key in the hash.

Passing references to subroutines One of the strengths of references is the ability to pass references to arrays and hashes to subroutines. This allows more than one array or hash to be passed properly to a subroutine. Since the code: sub twoarrays { does not work, as both arrays are joined into one references provide a way to pass scalars which reference more than one array.

Passing arrays To pass two arrays to a subroutine, you could passarray($refarray1, $refarray2); sub passarray { = statements…} and both arrays can be used inside the passarray subroutine by dereferencing the references.

Exercise Create two arrays, one holding vowels and the other holding consonants. Pass both arrays into a subroutine using references. Inside the subroutine, display all the elements of each array.

Great! See you next time!