1.0.1.8 – Introduction to Perl 10/20/2015 1.0.1.8.3 - Introduction to Perl - Lists and Arrays 1 1.0.1.8.3 Introduction to Perl Session 3 · lists and arrays.

Slides:



Advertisements
Similar presentations
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.
Advertisements

ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
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.
Sorting Algorithms. Motivation Example: Phone Book Searching Example: Phone Book Searching If the phone book was in random order, we would probably never.
Lists Introduction to Computing Science and Programming I.
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.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
2ex.1 Lists and Arrays. 2ex.2 Comments on exercises Always run your script with “ perl -w ” and take care of all warnings  submitted scripts should not.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
PERL Variables and data structures Andrew Emerson, High Performance Systems, CINECA.
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
CPTG286K Programming - Perl Chapter 3: Arrays and List Data.
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.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
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.
If statements while loop for loop
– Introduction to Perl 10/24/ Introduction to Perl - Hashes and Sorting Introduction to Perl Session 4 · hashes · sorting.
– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms Introduction to Perl Session 8 · recipes and.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CS 330 Programming Languages 10 / 07 / 2008 Instructor: Michael Eckmann.
Data structures Abstract data types Java classes for Data structures and ADTs.
– Intermediate Perl 6/3/ Intermediate Perl - sort/grep/map Intermediate Perl – Session 4 · scope · strict pragma · my.
Built-in Data Structures in Python An Introduction.
Chapter 9: Perl Programming Practical Extraction and Report Language Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
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
Project 1: Using Arrays and Manipulating Strings Essentials for Design JavaScript Level Two Michael Brooks.
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.
– Introduction to Perl 12/12/ Introduction to Perl - Searching and Replacing Text Introduction to Perl Session 7 ·
1 More Perl Strings References Complex data structures –Multidimensional arrays Subprograms Perl OOP –Methods –Constructors and Instances –Inheritance.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
LING/C SC/PSYC 438/538 Lecture 8 Sandiway Fong. Adminstrivia Homework 4 not yet graded …
Random Bits of Perl None of this stuff is worthy of it’s own lecture, but it’s all a bunch of things you should learn to use Perl well.
– Introduction to Perl 12/13/ Introduction to Perl - Strings, Truth and Regex Introduction to Perl Session 2 · manipulating.
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.
© Oxford University Press All rights reserved. CHAPTER 6 STRINGS.
Pointers *, &, array similarities, functions, sizeof.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Perl Scripting III Arrays and Hashes (Also known as Data Structures) Ed Lee & Suzi Lewis Genome Informatics.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
2.1 Scalar data - revision numeric e-14 ( = 6.35 × )‏ operators: + (addition) - (subtraction) * (multiplication) / (division)
Variables and Strings. Variables  When we are writing programs, we will frequently have to remember a value for later use  We will want to give this.
COMPUTER PROGRAMMING 2 ArrayLists. Objective/Essential Standard Essential Standard 3.00Apply Advanced Properties of Arrays Essential Indicator 3.02 Apply.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Python 1 SIGCS 1 Intro to Python March 7, 2012 Presented by Pamela A Moore & Zenia C Bahorski 1.
Programming Perl in UNIX Course Number : CIT 370 Week 2 Prof. Daniel Chen.
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.
Operators. Perl has MANY operators. –Covered in Chapter 3 of Camel –perldoc perlop Many operators have numeric and string version –remember Perl will.
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.
Data types: Complex types (List)
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,
Perl Variables: Array Web Programming.
Object Oriented Programming in java
CS 1111 Introduction to Programming Fall 2018
String and Lists Dr. José M. Reyes Álamo.
CS 1111 Introduction to Programming Spring 2019
Presentation transcript:

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays Introduction to Perl Session 3 · lists and arrays · for loop · context do this for clarity and conciseness Perlish construct unless you are a donkey, don’t do this

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 2 Recap · scalar variables are prefixed by $ and can contain characters or numbers · we saw the, as the list operator · recall substr(STR,OFFSET,LEN,NEWSTR) was used to isolate parts of a string, and · return a substring · replace the isolated substring with another string STR · if LEN=0 then NEWSTR is inserted · if LEN>0 and NEWSTR=“” then part of STR is deleted print $a,$b,$c ; ($a,$b,$c) = (1,2,3) ; # deletes first 3 characters# inserts $new at 5th character substr($string,0,3,””);substr($string,5,0,$new); a list

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 3 A New Variable – the Array · recall that Perl variables are preceded by a character that identifies the plurality of the variable · today we will explore the array variable, prefixed · the variable “type” is array but the variable holds a list · remember the stretched soup in can analogy animal scalararrayhash

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 4 Initializing Arrays · to initialize the array, pass a list · we initialized a scalar by passing a single value · an array variable is independent from a scalar variable of the same name · this is very important and can lead to confusion · arrays typically have plural names # $x is a scalar $x = 2; is an = (1,2,3); # while $dog are independent, different variables, # their identical names can lead to confusion $dog = = (“biff”,”bark”,”howl”);

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 5 Quote Word Operator · recall the use of qw( ) to easily define lists without typing quotes · qw() returns a list and it is natural to assign the output to an array · what happens when you try to assign output of qw() to a scalar? # initialize three scalars ($x,$y,$z) = qw(biff bark howl); # initialize an = qw(biff bark howl); # assign a list to a scalar? we'll see the results shortly $x = qw(biff bark howl);

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 6 Initializing with split · remember split – the operator that broke up a string along a boundary # split along any amoun of whitespace $string = “a b c d e”; ($a,$b,$c,$d,$e) = split(“ = split(“ “,$string); # split along a single character $string = = split(“:”,$string); # split along a string matching a regex $string = = split(/\d+/,$string);

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 7 Initializing With a Range · recall that we used a range of letters when defining a character class in regular expressions · you can create a list made up of a range of numbers (successive values) using.. · num..num (1..10) or char..char (a..z) # all letters a-to-z (a,b,c,...,z) $is_match = $x =~ /[a-z]/; (1..10) equivalent to (1,2,3,4,5,6,7,8,9,10) but also qw( )

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 8 Accessing Array Elements · an array is an ordered set of elements · elements are indexed by integers · first element is indexed by 0 (0-indexing) · if an array has n elements, last element is indexed by $animals[1] $animals[2] $animals[n-1] … array variableindividual elements

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 9 Accessing Array Elements · you may find the fact that the array is prefixed but its elements are prefixed with $ counter-intuitive · you’ll see why this is later – think “arrays store lists of scalars” # an array of numbers 1 to = (1..10); print $nums[0];1 print $nums[1];2 print $nums[2];3 print $nums[9];10 # $nums[10] is not defined, has 10 elements print $nums[10]; “” # settings element values $nums[5] = 50; $nums[6] = 60; print $nums[5];50 print $nums[6];60 print $nums[5],$nums[6];50 60

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 10 Negative Indexing · recall that substr had facility to accept negative offsets to indicate distance from the end of the string · array elements can be accessed similarly # an array of numbers 1 to = (1..10); # last element print $nums[-1];10 # second-last element print $nums[-2];9 # first and last elements print $nums[0],$nums[-1]; 1 10

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 11 Iterating Over an Array · the for loop (foreach is a synonym) permits you to iterate across a list · you will likely see foreach a lot, but I prefer the shorter = (1..5); for $num { print $num,” “,$num*$num,”\n”; } foreach $num { CODE }is the same as for $num { CODE }

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 12 Iterating Over an Array · you can iterate over the elements or array indices · choose the first approach if you don’t need to determine an element’s ordinal = (1..5); # iterate over elements for $item { print $item,”\n”; } # iterate over indices for $i (0..4) { print $x[$i],”\n”; }

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 13 Iterating Over an Array · a short script that prints the element of an array along with a “this is the nth element” = (1..5); # iterate over indices for $i (0..4) { print qq(This is the ${i}th element : $x[$i]); = (1..5); # iterate over elements, keep counter $counter = 0; for $num { print qq(This is the ${counter}th element : $num); $counter = $counter + 1: } this approach is preferred this approach is unnecessarily verbose

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 14 Adding to an Array with Push · there are many ways to add elements to an array · the most common is push · push adds elements to the end of the = (); # push single elements now (1) 2; now (1,2) now (1,2,3) # push a list of elements 4, now (1,2,3,4,5) qw(6 7); now = @x now (1,2,3,4,5,6,7,8,9,10)

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 15 Initializing an Array with Push · you can use for to initialize an array · frequently used with push, which adds elements to the end of an = (); for $num (1..10) { $num2 = $num*$num; $num2; print qq(added $num2, now last element is $x[-1]); } added 1, now last element is 1 added 4, now last element is 4 added 9, now last element is 9... added 100, now last element is 100

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 16 Arrays Grow as Necessary · you may have noticed that we did not need to allocate memory for the array when we defined it · the array variable grows and shrinks as necessary to accommodate new elements · in this example we defined the 4th element, $x[3], without explicitly definining the 3rd element, $x[2] – Perl created memory space for $x[2] and set the value to = (); $x[0] = now (1) $x[1] = now (1,2) $x[-1] = now (1,3) $x[3] = now (1,2,undef,4)

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 17 Arrays May Have undef Elements at End · the last defined element marks the end of the array · this applies when initializing array elements with defined elements (i.e. not undef) · setting the last element to undef, does not shrink the array · memory is allocated, but contents are = (); $x[5] = now (undef,undef,undef,undef,undef,5) $x[4] = now = now (1,2,3,4,5) $x[4] = now (1,2,3,4,undef) $x[3] = now (1,2,3,undef,undef)

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 18 Shrinking an Array · to extract the last element and shrink the array use pop · shift is more popular than pop, which extracts the first element, while also shrinking the = = (1,2,3,4,5); $y = $y = = (1,2,3,4) $y = $y = = (1,2,3) $y = $y = = (1,2) $y = $y = = (1) $y = $y = = () $y = $y = = = = (1,2,3,4,5); $y = $y = = (2,3,4,5) $y = $y = = (3,4,5)...

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 19 Arrays Grow and Shrink as Necessary · in this example an array is created and then repeatedly elements are removed · one element removed with pop – from the back · one element removed with shift – from the = (1..10); for $iteration (1..5) { my $x_popped = my $x_shifted = print qq(on iteration $iteration shifted $x_shifted and popped $x_popped); } on iteration 1 shifted 1 and popped 10 on iteration 2 shifted 2 and popped 9 on iteration 3 shifted 3 and popped 8 on iteration 4 shifted 4 and popped 7 on iteration 5 shifted 5 and popped 6

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 20 $#array · what the is this? · you’ve never seen this before, but you can guess what this variable holds · because it is prefixed by $, it holds a scalar value · $#array holds the index of the last element in the array · I dislike $#array – it is too noisy · we’ll see a cleaner alternative = (1..5); $last_idx = $#x;# $last_idx = 4 for $i (0..$last_idx) { print qq($i $x[$i]); } for $i (0..$#x) { print qq($i $x[$i]); }

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 21 Manipulating Array Contents · for now, these are the three ways to manipulate an array you need to be familiar with · remember that push can add a single element, or a list · shift/pop only remove one element at a time ( $x[0],$x[1],$x[2],…,$x[n-1], ) push shiftpop $#x

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 22 Swapping Elements · swapping elements is trivial – this may surprise you · $x[1] is assigned to $x[0] and $x[0] is assigned to $x[1] simultaneously · there is no need for a temporary variable to hold one of the values · temp  x0 ; x0  x1 ; x1  temp # consider swapping the values of two scalars $a = 5; $b = 6; ($a,$b) = ($b,$a); # apply the same to = (1,2); ( $x[0], $x[1] ) = ( $x[1], $x[0] );

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 23 Swapping Elements · let’s randomly shuffle elements in an array by pair-wise = (1..5) = (1,2,3,4,5) ($x[0],$x[-1]) = ($x[-1],$x[0]); = (5,2,3,4,1) ($x[0],$x[5]) = ($x[-1],6); = = (1..10); for $swap_count (1..5) { $i = int rand(10); # random integer in range [0,9] $j = int rand(10); # random integer in range [0,9] ( $x[$i], $x[$j] ) = ( $x[$j], $x[$i] ); print qq(swapped $i $j array is now ). join(" } swapped 5 4 array is now swapped 1 4 array is now swapped 5 8 array is now swapped 5 6 array is now swapped 7 2 array is now

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 24 Introduction to Context · make sure you are sitting comfortably – you are about to experience context · context refers to the immediate code around a variable or operator that influences how the variable or operator are interpreted · consider the following, in which we assign the output of a function to a scalar · Perl has the facility to determine that we are assigning the result of function( ) to a scalar and can act accordingly · the function could behave differently if we assign its output to an array · for example, function($n) could return · in scalar context - number of perfect squares from 0..$n · in array context – the list of perfect squares from 0..$n $x = = function();

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 25 Introduction to Context · what do you think happens in these two cases · in case 1, we are assigning an array to an array · Perl will copy the contents of to · the two arrays will have the same contents · the two arrays will be independent copies – changing one will not affect the other · in case 2, we are assigning an array to a scalar · Perl interprets the in scalar context · Perl returns the number of elements · $y now holds the length of the # case 1# case

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 26 Determining the Length of an Array · to obtain the number of elements in an array, evaluate it in scalar context · since arrays are 0-indexed, an array with n elements has its last index = (1..5); # scalar  array $len print “array has $len = (1..5); $len for $i (0..$len-1) { print qq(The ${i}th element is $x[$i]); }

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 27 $#x · recall that $#x provided the index of the last element in an array in a scalar context gives the number of elements is easier on the eyes · $#x has its uses, however · recall that substr( ) could extract parts of a string, but was also an l-value · well, $#x is also an l-value · you can assign a value to $#x to explicitly set the index of the last element, effectively growing/shrinking the array $#x is the same - = (1..5); print $#x;# 4 $#x = = (1,2,3,4,5,undef) $#x = = (1,2,3,4) $#x = = (1,2,3,4,undef,undef)

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays 28 More About Context · context helps you write concise code – tread = (1..5); # what is the value of $y? $y + = (1..5); # why does this work? for $i { print qq($i $x[$i]); = (1..5); # what is happening here? what is the last line printed? for $i { print qq($i $x[$i]); }

– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays Introduction to Perl Session 3 · you now know · all about arrays · declaring and initializing an array · growing and shrinking arrays · extracting elements and length of an array · for loop · iterating over arrays by element or index · application of split and join to arrays · context · next time · hashes