1.0.1.8 – Introduction to Perl 10/25/2015 1.0.1.8.8 - Introduction to Perl - Recipes and Idioms 1 1.0.1.8.8 Introduction to Perl Session 8 · recipes and.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Introduction to Ruby.
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.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
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.
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
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.
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.
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.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
CS311 – Today's class Perl – Practical Extraction Report Language. Assignment 2 discussion Lecture 071CS Operating Systems I.
COS 381 Day 19. Agenda Questions?? Resources Source Code Available for examples in Text Book in Blackboard
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
Sorting. Simple Sorting As you are probably aware, there are many different sorting algorithms: selection sort, insertion sort, bubble sort, heap sort,
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.
 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.
CSE S. Tanimoto Perl Arrays, Functions, Lists, Refs, Etc 1 Perl: Arrays, Functions, References, Etc. Arrays Slices, splices Contexts: list, scalar.
Introduction to Perl Part III By: Cedric Notredame Adapted from (BT McInnes)
Tutorial 14 Working with Forms and Regular Expressions.
1 An Introduction to Perl Part 2 CSC8304 – Computing Environments for Bioinformatics - Lecture 8.
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
CPTG286K Programming - Perl Chapter 3: Arrays and List Data.
ASP.NET Programming with C# and SQL Server First Edition Chapter 5 Manipulating Strings with C#
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.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
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.
– Introduction to Perl 10/24/ Introduction to Perl - Hashes and Sorting Introduction to Perl Session 4 · hashes · sorting.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
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.
Introduction to Perl Part III By: Bridget Thomson McInnes 6 Feburary 2004.
Chapter 9: Perl (continue) Advanced Perl Programming Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
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
5 1 Data Files CGI/Perl Programming By Diane Zak.
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 ·
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,
– Introduction to Perl 12/13/ Introduction to Perl - Strings, Truth and Regex Introduction to Perl Session 2 · manipulating.
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.
Topic 2: Working with scalars CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 2, pages 19-38, Programming Perl 3rd edition chapter.
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.
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)
Python Programing: An Introduction to Computer Science
Arrays and Lists. What is an Array? Arrays are linear data structures whose elements are referenced with subscripts. Just about all programming languages.
Variable Variables A variable variable has as its value the name of another variable without $ prefix E.g., if we have $addr, might have a statement $tmp.
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.
Dept. of Animal Breeding and Genetics Programming basics & introduction to PERL Mats Pettersson.
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.
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.
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,
LING/C SC/PSYC 438/538 Lecture 4 Sandiway Fong.
Strings Part 1 Taken from notes by Dr. Neil Moore
Perl Variables: Array Web Programming.
Chapter 10 Lists.
Context.
String and Lists Dr. José M. Reyes Álamo.
String Processing 1 MIS 3406 Department of MIS Fox School of Business
Introduction to Computer Science
Introduction to Computer Science
Presentation transcript:

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms Introduction to Perl Session 8 · recipes and idioms · where to go from here

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 2 Setting a Default Value · the op= operator is a useful shortcut · a = a + b  a += b · a = a * b  a *= b · a = a || b  a ||= b · remember the difference between false and defined · zero is false, but defined # force default value if variable is false $x ||= 5; # set default values for input arguments func($x,$y); sub func { my $x = shift; # method A – shift or default my $y = shift || 5; # method B – shift, then default my $y = shift; $y || = 5; }

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 3 defined-or · Perl 5.10 adds a new type of OR which uses if defined rather than if · use // when false (0) is an acceptable value # the defined-or# the standard or $c = $a // $b;$c = $a || $b# equivalent to if(defined $a) {if($a) { $c = $a $c = $a;} else { $c = $b;} # $a=0 is a perfectly good value, which will be honoured # $a  10 assignment will happen only when $a is undefined $a //= 10; # compare the above to ||=, for which 0 is not an acceptable value # here, $a  10 assignment will happen when $a is false $a ||= 10;

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 4 Swapping Values · to swap values, Perl does not require a temporary variable # initialize separately $a = 5; $b = 10; # initialize together ($a,$b) = (5,10); # swap simultaneously # a  10 b  5 ($a,$b) = ($b,$a);

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 5 Processing Strings One Character at a Time · to split a string into component characters, use split with empty boundary · you can also use a while loop with global captured search # initialize separately $string = “wooly sheep”; # split (//,$string) also works # split (undef,$string) also = split(“”,$string); for $char { print qq{give me an $char!}; } # initialize separately $string = “wooly sheep”; # split (//,$string) also works while( $string =~ /(.)/g ) { print qq{give me an $1!}; }

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 6 Match with Confidence · test whether a regex matches a string in scalar context · returns 0/1 if REGEX is found anywhere within the string · pull out all matches using list context and /g · you must use /g or you will only get the first match $found_match = $string =~ = $sequence =~ /atgc/g; # extract subpatterns with capture = $sequence =~ /aaa(...)aaa/g;

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 7 counting characters in a string · recall that =~ with /g returned all matches · use =~ tr/// to count $x = = $x =~  qw(a a a a) # to count the number of matches, force =~ to be evaluated in list context first, # then evaluate in scalar context $n = () = $x =~ /a/g; $n  4 $n = $x =~ /a/g; does not work - =~ is evaluated in scalar context $n  1 ($n) = $x =~ /a/g does not return count – returns first match $n  "a" $x = "aaaabbbccd"; $n = $x =~ tr/a//;

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 8 Reversing Lists · to reverse a list or string, don’t forget the reverse operator · in scalar context · if passed a scalar, reverses the characters in the scalar – e.g, sheep  peehs · if passed a list, reverses the list and returns a concatenated list – e.g., qw(1 2 3)  "321" · in list context, reverses a list and returns it – e.g., qw(1 2 3)  qw(3 2 = split(“”,"sheep");  qw(s h e e p) # scalar context, passed a scalar $string_rev = reverse “sheep”;  peehs # list context, passed a =  qw(p e e h s) # scalar context, passed a list $string_rev =  peehs # challenge print reverse “sheep”;  sheep print $y = reverse “sheep”;  peehs

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 9 Parsing Out Substrings · to extract parts of input strings, use regexs and capture brackets · the first example works because =~ is called in list context · returns all matching strings (optionally delineated by capture brackets) · the second example works because pattern buffers $1,$2 are set after a successful match ($w,$h) = $message =~ /screen size is (\d+) by (\d+) pixels/; # or verbosely if( $message =~ /screen size is (\d+) by (\d+) pixels/ ) { ($w,$h) = ($1,$2); }

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 10 Trimming Strings · chomp is used to safely remove a newline from the end of a string · other leading/trailing characters are commonly discarded · spaces · zeroes · non-word characters # remove leading spaces $x =~ s/^\s*//; # remove trailing spaces $x =~ s/\s*$//; # remove both leading and trailing spaces $x =~ s/^\s*(.*?)\s*$/$1/; # challenge – why not the following regex? $x =~ s/^\s*(.*)\s*$/$1/;why is the ? important? # remove leading zeroes $x =~ s/^0*//; # remove a variety of leading characters $x =~ s/^[0\s;]*//;

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 11 Creating Integer Ranges · use the range operator.. to create ranges of integers, or even = = reverse (10..20); for (10..20) { print; } # range of characters for (a..z) { $alphabet.= $_; } $alphabet = join(““,(a..z));

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 12 Using Array Slices · an array slice is a list of several array elements · you specify a set, or range, of indeces and obtain a list of corresponding elements · syntax is a little wonky, but makes sense if you think about = (0..9); $list[0] first element $list[1]second element ($list[0],$list[1])first, second second three elements elements $list[0]element, scalar list context – same as ($list[0]) # array in original order # two ways to reverse an array – reverse elements or ];

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 13 Using Modules · modules are collections of Perl code written by other users that perform specific tasks · modules can be downloaded from CPAN – Comprehensive Perl Archive Network · search.cpan.org

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 14 Math::VecStat · a simple module is Math::VecStat · provides statistics about a list: min, max, average, sum, and so on · import the module by use · some module require that you specify which functions you wish to import into your namespace · CPAN provides documentation about each module · man Math::VecStat use Math::VecStat qw(average sum); # both functions have been imported into current namespace $avg = $sum = # we didn’t import this function, so must call it explicitly $min =

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 15 Fetching Current Date · the main date function is localtime · list context returns · $sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst · month is 0-indexed !!! · add 1900 to year !!! · scalar context returns formatted date $date = localtime; print $date; Tue May 30 14:11:56 = localtime; printf(“day %d month %d year %d”,$list[3],$list[4],$list[5]); day 8 month 6 year 108 printf(“day %d month %d year %d”,(localtime)[3,4,5]);

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 16 Getting Epoch Value · the UNIX epoch value is seconds since epoch · turn of epoch is Thu Jan (UTC) · use timelocal from Time::Local module · use localtime(EPOCH) to convert back to date = localtime; # fetch the current day, month and year via array slice ($s,$min,$h,$d,$mm,$y) # determine turn of epoch right now $epoch = timelocal($s,$min,$h,$d,$mm,$y); # timelocal is the reverse of localtime – turns S,M,H,D,M,Y into epoch time $epoch = timelocal( (localtime)[0..5] ); # epoch midnight tonight print timelocal( 0,0,0, (localtime)[3..5] );

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 17 Changing Array Size · you grow an array by allocating new values · recall in scalar context gives the size of list (number of elements) · $#list is the index of the last element · = (); $list[99] = 1; # you now have a 100 element array $list[99] = undef; # you still have a 100 element array – you cannot shrink array by setting # elements to ‘undef’ since ‘undef’ is a perfectly good element value $#list = 9; # you now have a 10 element array – explicitly set the index of last element

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 18 Be wary of $_ · the current iterator value is $_ · $_ is an alias · whatever $_ points to, can be altered in place for { # read-only access to elements - good print $_; } for { # you are altering $_ - since $_ is an alias, you are $_++; }

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 19 Adding/Removing Elements from a List · you cannot have a list of lists, unless you use references · if you combine two lists, you will get a single, flattened list · remove elements with shift (from the front) or pop (from the back) # all these are valid ways to extend a list @list = # = $x = # = $x =

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 20 Randomizing a List · randomize a list by using a random sort routine # ascending numerical = sort { $a $b # random sort – shuffle # pair-wise comparison independent of actual values – returns -1,0,-1 = sort { rand() rand() # shuffle the list by shuffling indices, not sort { rand() rand() } ];

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 21 Using Hashes Effectively · use a hash when storing relationships between data · fruit and color · base pair and frequency · this example is artificial – you'll see better ways to do this when see references # contains a list of clones, e.g, qw(A0001A01, A0001B01, etc) for { $count{$_}++; } # use hashes to store pair-wise relationships for $i { for $j { ($ci,$cj) if(clones_overlap($ci,$cj)) { $overlap{$ci}.= $cj; # e.g., $overlap{A0001A01} = "A0012F01A0018G03A0024B03" $overlap{$cj}.= $ci; } # now extract names of all clones that overlap = $overlap{$clonename} =~ /.{8}/g;

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 22 Deleting from a Hash · the only way to remove a key from a hash is to use delete $hash{sheep} = “wooly”; $hash{sheep} = undef; # key sheep still exists, points to ‘undef’ value if(exists $hash{sheep}) { # yup – key exists and this code runs } delete $hash{sheep}; if(exists $hash{sheep}) { # nope – key does not exist and this code does not run }

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 23 Copy and Substitute in a Single Step · copying a string and modifying it is a very common pair of steps · you can do both in one shot · you must use the brackets, or precedence will kill you · challenge – what is assigned to $y? $y = $x; # copy $y =~ s/sheep/pig/g; # substitute ($y = $x) =~ s/sheep/pig/g; $x = “aaa”; $y = $x =~ s/a/b/; # what is $x and $y ? $y = $x =~ s/a/b/g; # what is $x and $y ?

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms 24 Morals · print evaluates its arguments in list context – watch out! · undef is a perfectly good value for a list or hash element · shrink lists by adjusting #$list · delete keys by using delete · distinguish between testing for truth (zero not ok) or definition (zero ok) · $_ is an alias, not a copy of a value · do not adjust the value of $_ unless you are sure-footed · character class [abc] matches only one character, not three · for and foreach are synonymous · qq{} interpolates but q{} does not · use (m..n) range operator where possible (m  n) · keys/values return elements in no particular (but compatible) order · replace strings with s/// rather than substr · s/REGEX/REPLACEMENT/ - the second argument is not a regex

– Introduction to Perl 10/25/ Introduction to Perl - Recipes and Idioms Introduction to Perl Session 8 · congratulations!