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.

Slides:



Advertisements
Similar presentations
Chapter 3: Control Flow S. M. Farhad. Statements and Blocks An expression becomes a statement when it is followed by a semicolon Braces { and } are used.
Advertisements

CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
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.
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.
References and Data Structures. References Just as in C, you can create a variable that is a reference (or pointer) to another variable. That is, it contains.
Perl Arrays and Lists Software Tools. Slide 2 Lists l A list is an ordered collection of scalar data. l A list begins and ends with parentheses, with.
Input from STDIN STDIN, standard input, comes from the keyboard. STDIN can also be used with file re-direction from the command line. For instance, if.
Lists Introduction to Computing Science and Programming I.
Perl Arrays and Lists Learning Objectives: 1. To understand the format and the declaration of Arrays & Lists in Perl 2. To distinguish the difference between.
Perl I/O Learning Objectives: 1. To understand how to perform input from standard Input & how to process the input 2. To understand how to perform input.
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
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.
Scalar Variables Start the file with: #! /usr/bin/perl –w No spaces or newlines before the the #! “#!” is sometimes called a “shebang”. It is a signal.
Hashes a “hash” is another fundamental data structure, like scalars and arrays. Hashes are sometimes called “associative arrays”. Basically, a hash associates.
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
Perl I/O Software Tools. Lecture 15 / Slide 2 Input from STDIN Reading from STDIN is easy, and we have done it many times. $a = ; In a scalar context,
Sorting. Simple Sorting As you are probably aware, there are many different sorting algorithms: selection sort, insertion sort, bubble sort, heap sort,
25-Jun-15 JavaScript Language Fundamentals II. 2 Exception handling, I Exception handling in JavaScript is almost the same as in Java throw expression.
Perl File I/O and Arrays. File I/O Perl allows to open a file to read, write, or append As well as pipe input or output to another program. —We get to.
JavaScript, Third Edition
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
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.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
by Chris Brown under Prof. Susan Rodger Duke University June 2012
IE 212: Computational Methods for Industrial Engineering
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.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
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.
CPTG286K Programming - Perl Chapter 3: Arrays and List Data.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CS 330 Programming Languages 10 / 07 / 2008 Instructor: Michael Eckmann.
Built-in Data Structures in Python An Introduction.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
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”
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 5 Hashes. Outside of world of Perl, know as associative arrays Also called hash tables Perl one of few languages that has hashes built-in.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83,
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.
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.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Fluency with Information Technology Third Edition by Lawrence Snyder Chapter.
Topic 3: Lists and arrays CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 3, pages 40-55, 86-91, Programming Perl 3rd edition.
Working with Loops, Conditional Statements, and Arrays.
2.1 Scalar data - revision numeric e-14 ( = 6.35 × )‏ operators: + (addition) - (subtraction) * (multiplication) / (division)
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Arrays and Lists. What is an Array? Arrays are linear data structures whose elements are referenced with subscripts. Just about all programming languages.
CSC 4630 Perl 2 adapted from R. E. Beck. I/O and Arithmetic Form pairs of programmer/investigator/discover Exercise 1. Write a program that prompts the.
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.
Introduction to Programming the WWW I CMSC Winter 2004 Lecture 8.
Input from STDIN STDIN, standard input, comes from the keyboard.
Containers and Lists CIS 40 – Introduction to Programming in Python
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
Stack Data Structure, Reverse Polish Notation, Homework 7
Perl Variables: Array Web Programming.
Conditions and Ifs BIS1523 – Lecture 8.
Bryan Burlingame 03 October 2018
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
CS190/295 Programming in Python for Life Sciences: Lecture 6
Context.
Perl I/O Learning Objectives:
Introduction to Computer Science
Presentation transcript:

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. You dont have to declare a maximum size: Perl automatically enlarges the array as needed during execution of the program.

Literal Lists A list is a set of elements enclosed within parentheses and separated by commas. String elements must be quoted. You can mix numerical and string values (1,3,5) is a list. So is (1, , duh). The empty list is (). Range operator: (1..5) creates a list (1, 2, 3, 4, 5). It adds in all elements from the left to the right by adding 1 to the previous value. The qw shortcut: If you want to enter a long list of strings, it is annoying to keep putting in all the quotes and commas. qw does this for you. Thus, qw(dog cat bird) is the same as (dog, cat, bird). This is a commonly used construction. Amusingly, you can use delimiters other than parentheses: qw! dog cat bird ! works just fine. Usually a bad idea, I suspect.

Array Variables Array variables start Arrays are treated differently from scalar variables. Assigning to an array. One way is to assign a = (1, 3, 5); You can also assign lists to each other this way: ($cat, $dog, $horse) = (1, 3, 5); Switching positions of 2 variables requires use of a third variable in C. In Perl: ($cat, $dog) = ($dog, $cat);

More of List Assignment If you have fewer elements on the left than on the right, the remaining elements on the right are ignored: ($dog, $cat) = qw(rover spot fido); causes $dog to have the value rover, and $cat to be spot. fido is simply not used. On the other hand, ($dog, $cat, $bird) = (rover, $spot); assigns names to $dog and $cat, but $bird keeps its initial value of undef. If an array variable is used on the left side of an assignment, it slurps up all remaining values on the right. ($dog, = qw( rover fido spot rex duke fluffy); gives names to $dog and gets al the rest: spot, rex, duke, and fluffy. But more subtly: $dog, $cat) = qw( rover fido spot rex duke fluffy); to get all the names, and $dog and $cat to remain undefined. And, $cat) = qw( rover fido spot rex duke fluffy); assigns rover to $dog and all the rest of the names $cat remains undef.

Printing an Array will print all elements of the array run together. (1, 3, 5); produces: 135. separates the elements with a space:

Accessing Array Elements Just as in C, array elements are in sequential order, starting with element 0, and they are accessed through array indices enclosed in square brackets. An array taken as a whole, is a plural object that for instance. However, individual array elements are scalars, and start with a $: $arr[0] is the first element $arr[1] is the second element, etc. $arr, without any index, is an entirely separate variable, having nothing whatsoever to do

More On Array Indices You can use a variable as an array index: $index = 3; print $arr[3]; print $arr[ $index ]; Gives the same result. Indices can be non-integers: they are simply truncated to the integer part when used as an index Negative numbers are used to access array elements from the end: $arr[-1] returns the last element in the array, $arr[-2] returns the next-to-last element, etc. $#arr gives the index of the last array element. Thus $arr[-1] == $arr[ $#arr ]; Very useful for loops.

Array Slices It is possible to access just part of an array, a slice of an array. For 4, 7, 9..12]; This creates the containing elements 0, 4, 7, 9, 10, 11, and 12 Note that a slice is itself is an array, and in front of it.

List Operators You can easily add or remove elements from either end of an array. push and pop operate on the end (right side) of an array. They treat the array as a stack. 7); adds the element 7 to the end of the array. $num = removes the last element (i.e. $arr[-1] ) and assigns it to $num. shift and unshift work on the beginning (left end) of the array. 9; puts the element 9 at the beginning of the array (i.e. $arr[0] ) and shifts all the other elements up one position. $num = removes the first array element and assigns it to $num. The other array elements move down one position in the array.

More List Operators reverse reverses the elements of an array. That is, it returns the elements in reverse order. You need to assign this functions reverse value to another array if you want to use = Or you can just assign it right back to the original = sort sorts the array. We will discuss this function in more depth later, but for now, there are 2 forms of sort that are useful: 1. sort in ASCII order (default for = 2. sort in numerical = sort {$a Quite a construction--be sure to copy it accurately when you use it. In particular, you must use $a and $b as indicated.

For Loops Perl uses two different constructions for loops. The first is the standard C style loop, a 3 part clause separated by semicolons: for ($i = 0; $i < 10; $i++) { do something; } The first part initializes the loop counter variable. The second part is a test: each time the program reaches the top of the loop, this clause is re-evaluated. If true, the loop is executed, and if false the program passes to the next statement. The third part changes the loop counter each time the loop finishes execution.

Foreach Perl has an alternate loop construction. For convenience the key word is foreach. However, the keyword for will also work for this type of loop. Sometimes called the indirect object form. foreach $element ) { do something; } each element is substituted into $element and the loop is executed, until all the array elements have been used. Note that you arent using array indices here at all, just the elements themselves. You can use the indices with a construction like: foreach $index ( 0.. $#arr) { something; } You can use a list instead of an array: foreach $pet ( cat, dog, bird) { }

$_, the Default Variable In many cases, if you dont assign input to a variable, Perl automatically assigns it to the variable $_, which can often be used without being written explicitly. while ( ) { print; } The input from STDIN is assigned to $_, and the $_ is printed, without ever being directly mentioned. Another major use is in foreach loops: foreach { print; } # prints roverspotfido foreach { print $_, ; } # prints rover spot fido Note that sometimes it is necessary (or merely useful) to write $_ into the code. Although it seems a small thing, use of $_is widespread in Perl, and saves a lot of time.

Scalar vs. List Context Here is one of the more subtle concepts in Perl, and you need to pay attention now. Some Perl expressions act differently depending on how they are used: their context. We have seen a small bit of this already: $var = 5 + 3; print $var; give 8 $var = 5. dog; print $var; gives 5dog. In the first case, 5 is treated as a numerical value, because you are adding a number to it. In the second case, 5 is treated as a string, because you are concatenating another string to it.

Scalar vs. List Context, p. 2 Arrays themselves can be used in scalar or list and both in list context. But what about: $var is being used in scalar context; it is being assigned to a scalar variable. In this case, the value returned is the number of elements in = (1, 3, 5, 7); gives ; but: $var print $var; gives 4 (the number of elements

Scalar vs. List Context, p. 3 Many functions usually produce a list. But, when used in scalar context (assigned to a scalar variable, for instance), they do something different. reverse is a good example of this. In list context, reverse returns the list in reverse order. In scalar context, reverse reverses a string (or reverses the result of concatenating the strings in a = reverse qw(dog cat bear); # gives bear, dog, cat $backwards = reverse qw(dog cat bear); # gives raebtacgod (Usually, reverse in scalar context is used on scalar strings: $backwards = reverse $sequence; ) Note that parentheses define a list context, and that some arrays are only 1 element long: $backwords = reverse rabbit; # gives tibbar ($backwards) = reverse rabbit; # gives rabbit, because reverse is used in list context on a 1 element array Some functions dont have a useful scalar context. For instance, using sort in a scalar context gives a value of undef.

Scalar vs. List Context, p. 4 A few miscellaneous things. Sometimes you need to force an array into scalar context. The keyword scalar does = (1, 3, 5, 7); # gives 1357 print # gives scalar print elements in array; # gives 4 elements in array in a list = ; Puts all the lines coming from STDIN into an array, one line per array element. Often used with file re-direction: on the command line test.pl < file.txt Can be used in tandem with chomp: = ); inputs all lines and removes the terminal \n from each of them.