1 Perl: arrays. 2 #!/usr/bin/perl -w # bind3.pl # # Here's an example that takes a unix path ($file) # and copies it to anothe variable ($filename) #

Slides:



Advertisements
Similar presentations
Chapter 25 Perl and CGI (Common Gateway Interface)
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.
C Language.
Arrays Strings and regular expressions Basic PHP Syntax CS380 1.
1 Perl Syntax: substitution s// and character replacement tr//
Dynamic Arrays Lecture 4. Arrays In many languages the size of the array is fixed however in perl an array is considered to be dynamic: its size can be.
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.
Programming Perls* Objective: To introduce students to the perl language. –Perl is a language for getting your job done. –Making Easy Things Easy & Hard.
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.
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.
Perl Basics A Perl Tutorial NLP Course What is Perl?  Practical Extraction and Report Language  Interpreted Language Optimized for String Manipulation.
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.
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.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
1 Operating Systems Lecture 3 Shell Scripts. 2 Brief review of unix1.txt n Glob Construct (metacharacters) and other special characters F ?, *, [] F Ex.
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.
An Introduction to Unix Shell Scripting
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
Print 'Hello world.'; Tren Griffith. Outline:  Perl introduction  Scalar Data  Variables  Operators  Control Structures  Input  Lists and Arrays.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
CPTG286K Programming - Perl Chapter 3: Arrays and List Data.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
– Introduction to Perl 10/20/ Introduction to Perl - Lists and Arrays Introduction to Perl Session 3 · lists and arrays.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
COMP519: Web Programming Autumn 2010 Perl Tutorial: The very beginning  A basic Perl Program The first line Comments and statements Simple printing 
Built-in Data Structures in Python An Introduction.
Books. Perl Perl (Practical Extraction and Report Language) by Larry Wall Perl 1.0 was released to usenet's alt.comp.sources in 1987 Perl 5 was released.
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.
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.
PERL Ronald L. Ramos Proglan. What is PERL? Perl stands for Practical Extraction and Reporting Language. (or Pathologically Eclectic Rubbish Lister).
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
Computer Programming for Biologists Class 3 Nov 13 th, 2014 Karsten Hokamp
Introduction to Perl “Practical Extraction and Report Language” “Pathologically Eclectic Rubbish Lister”
5 1 Data Files CGI/Perl Programming By Diane Zak.
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.
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,
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 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.
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.
Introduction to Perl NICOLE VECERE. Background General Purpose Language ◦ Procedural, Functional, and Object-oriented Developed for text manipulation.
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.
Perl Scripting III Arrays and Hashes (Also known as Data Structures) Ed Lee & Suzi Lewis Genome Informatics.
2.1 Scalar data - revision numeric e-14 ( = 6.35 × )‏ operators: + (addition) - (subtraction) * (multiplication) / (division)
COMPUTER PROGRAMMING 2 ArrayLists. Objective/Essential Standard Essential Standard 3.00Apply Advanced Properties of Arrays Essential Indicator 3.02 Apply.
Interpolation Variable Interpolation, Backslash Interpolation.
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.
2000 Copyrights, Danielle S. Lahmani Foreach example = ( 3, 5, 7, 9) foreach $one ) { $one*=3; } is now (9,15,21,27)
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.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
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.
Engineering Innovation Center
Perl Variables: Array Web Programming.
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
Programming Perls* Objective: To introduce students to the perl language. Perl is a language for getting your job done. Making Easy Things Easy & Hard.
int [] scores = new int [10];
Sorting "There's nothing in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The Sorting Hat, Harry Potter.
Arrays.
Sorting.
Presentation transcript:

1 Perl: arrays

2 #!/usr/bin/perl -w # bind3.pl # # Here's an example that takes a unix path ($file) # and copies it to anothe variable ($filename) # Then, we search for one or more of any character {.+} # followed by a "/" character -- but we have to use the # escape metacharacter "\" so that we don't end the match {\/}. # Finally, we are looking for one or more non-white spaces {(\S+) # at the end -- to pull off the the last file name "FOUND" # $path = "/home/tabraun/test/bob/FOUND"; $filename = $path; $filename =~ s/.+\/(\S+)/$1/; print "$filename\n";

3 #!/usr/bin/perl # randomSeq.pl # # Don't get too uptight over this line -- it is just setting # a "seed" for the rand() fuction with a value that approximates # a random number. If you must know, it takes a prccess ID ($$), # shifts its bit left 15 times, then add the process ID to the shifted # value, then does an bit-wise XOR (^) with the current time(). # print "Enter length of sequence to generate:"; $length = ; srand(time() ^ ($$ + ($$ << 15)) ); while($length) { # stay in loop until have generated enough sequence $rand = int rand(4); # Interger number between (0-3) inclusive $rand =~ tr/0123/ACTG/; $length = $length-1; #decrease loop counter $seq = $seq. $rand; #keep the nucleotide I just created } # Since I am out of the loop, I must be done print "$seq\n";

4 Run Example Show process ID

5 Lists and Arrays list – ordered collection of scalars array – a perl variable that contains a list each element of an array is a separate scalar variable values are ordered, from the first to the last elements are indexed by small integers, starting at "hello, world" 1.72e30 "bye\n" indices "left-most" "right-most"

6 Accessing Elements of an Array $fred[0] = "yabba"; $fred[1] = "dabba"; $fred[2] = "doo"; $fred[3] = 4; $fred[3]++; $fred[1] =~ s/b/B/g; $fred = 32; #completely different scalar

7 Creating Elements if you store into an array element that is beyond the end of the array, the array is automatically extended as needed (no limit as long as there is memory available) intervening elements will be undef $rocks[0] = 'bedrock'; $rocks[1] = 'slate'; $rocks[99] = 'chasm'; # 3 defined elements, 97 undef.

8 List Literals shorthand for creating arrays (1,2,3) #list of 3 values, 1, 2, 3 (1, 2, 3,) # same thing, last comma ignored ("fred",4.5) # 2 values () # empty list (1..100) # list of integers, 1 thru 100 # aka "range operator" (1..5) #1, 2, 3, 4, 5 (5..1) # empty, only counts up (0, 2..6, 10) #(0, 2, 3, 4, 5, 6, 10) ($a..$b) # depends on $a and $b

9 Another List Shortcut qw -- stands for "quoted words" ("fred", "barney", "betty", "wilma", "dino") same as qw/ fred barney betty wilma dino / #same as above with less typing

10 List Assignment list values may be assigned to variables ($fred, $barney, $dino) = ("finstone", "rubble", undef); can use to swap ($fred, $barney) = ($barney, $fred); Note – you cannot do this in most other languages (C, Java, etc) Extra right side values are ignored Extra left side variables will be undef ($fred, $barney) = qw/ flintstone rubble slate /; # slate ignored ($wilma, $dino) = qw/flintstone/; #dino gets undef

11 List Assignment can build array ($r[0], $r[1], $r[2]) = qw/ slate granite chalk/; one final array = qw/ bedrock slate lava/; $rocks[2] =~ = = (1..10); # 10 elements of #13 elements $dino = = $dino); Array names are replaced by the elements in its list

12 Copying an Array is # all elements are copied for($I=0;$I<$num;$I++) { $copy[$I] = $quarry[$I]; }

13 Array Manipulations could add to arrays by storing them into elements with new, larger indices however, this defeats the strengths of perl, and will actually result in slower code extensive use of indices slows down perl

14 Array as a Stack elements are added/removed from the "right" side of the list (portion with highest indices) Syntax push ARRAY, LIST - returns new number of elements in array pop ARRAY - returns “right” most element of = (5..9); # array has 5,6,7,8,9 $fred = # fred = 9, array = 5,6,7,8 $barney = #barney = 8, array = 5,6,7 # 7 is discarded, array = 5, 6

15 push 0); = (5, 6, 7);

16 An Array as a Queue Elements are added/removed from the left (or portion with lowest indices) shift ARRAY - returns ‘left’ most element unshift ARRAY, list - returns new number of elements in = qw/ dino fred barn /; $a = = fred, barn $b = = barn is empty $c = still empty, $c = undef now has = (1..4); = 1,2,3,4,5

17 Mix and = (9..13); 14); $fourteen = $nine = print "$array[2]";

18 Interpolating into Arrays Like scalars, array values my be interpolated into double-quoted = qw/ stone gravel rubble /; print marble\n"; #inserts spaces between elements of array print "$rocks[1]\n"; # gravel

19 Foreach loop revisited foreach SCALAR (ARRAY) { } -- steps through each item of an array executing one iteration each time thru the = qw /bedrock pebbles stone/; foreach $rock { print "One rock is $rock\n"; }

20 Control Loop Variable A change to the control loop variable actually changes the elements of the array. $rock = "Haggar"; #rock is stored and saved by = qw/ slate stone marble /; foreach $rock { $rock =~ s/(.*)/\U$1/; } print # SLATE STONE MARBLE print "$rock\n"; #Haggar restored ???

21 Other Array Operators reverse ARRAY -- takes an array of items and reverses the = = reverse = #fred is now reversed too reverse SCALAR -- in a scalar context, such as the string ATGCC, reverse will reverse the order of the string -- CCGTA

22 Other Array Operators sort ARRAY -- takes a list of values and sorts them in character order = qw/ slate stone marble = (97, 98, , = sort #marble slate = sorted #

23 Array-like Operator glob EXPR -- In list context, returns a (possibly empty) list of filename expansions on the value of EXPR such as the standard Unix shell /bin/csh would do = glob '*';

24 Examples Multiple syntax for arrays

25 End

26 Other topics sort reverse glob split system and ` ` array growth/memory allocation pop, push, shift, unshift slice building 2-d arrays arrays of hashes and hashes of arrays Other (modules, and module for long) –file tests –files and directories –cgi-bin –advanced sorting –strings

27 Side Note More on arrays in later lecture, however, question of arrays of arrays:

28 = = = (100,200,300,400,500); # is a = foreach $i # i becomes a reference to an array { foreach $j dereferences i (an reference to an aray) { # so j is an elemetn of an array print "$j is value in arrayArray\n"; } print "\n"; #### I much prefer this notation print "$numbers[2][3]\n"; print "\n"; # and finally for ($i = 0; $i $i++) { $aref = $numbers[$i]; #so bizzare, my editor for ($j = 0; $j <= $#{$aref}; $j++) { #thinks this is comment print "$numbers[$i][$j]\n" # $#ARRAY returns index of last element }

29./arrayArray.pl 1 is value in arrayArray 2 is value in arrayArray 3 is value in arrayArray 4 is value in arrayArray 5 is value in arrayArray 10 is value in arrayArray 20 is value in arrayArray 30 is value in arrayArray 40 is value in arrayArray 50 is value in arrayArray 100 is value in arrayArray 200 is value in arrayArray 300 is value in arrayArray 400 is value in arrayArray 500 is value in arrayArray

30 End

31 Example Negative numbers: in the sample source code I provided, I use the following REGEXP ^\d+$ to verify that a "number" was entered. Note that this will not match a negative number (as in the example I ran during class) because it does not include a "-" Note, you should only set the seed ONCE – doing so more often would actually decrease the approximation of a random number srand (time() ^ ($$ + ($$ << 15)) ); Examples What is "random" – how would you verify that your output is random? You would expect each letter to occur about 25% of the time../randSeq.pl > look cat look | grep A | wc OR count the letters as you generate them and print