CS 105 Perl: Basic I/O, Context, Strings, Lists Nathan Clement January 22, 2014.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
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.
Lecture 2 Introduction to C Programming
Introduction to C Programming
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
CSET4100 – Fall 2009 Perl Introduction Scalar Data, Operators & Control Blocks Acknowledgements: Slides adapted from NYU Computer Science course on UNIX.
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.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
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 Basics A Perl Tutorial NLP Course What is Perl?  Practical Extraction and Report Language  Interpreted Language Optimized for String Manipulation.
Bash, part 2 Prof. Chris GauthierDickey COMP Unix Tools.
Introduction to Perl. How to run perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Your program/script.
Perl Lecture #1 Scripting Languages Fall Perl Practical Extraction and Report Language -created by Larry Wall -- mid – 1980’s –needed a quick language.
Operators. Perl has MANY operators. –Covered in Chapter 3 of Prog.Perl Most operators have numeric and string version –remember Perl will convert variable.
Introduction to C Programming
Subroutines. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc We’ll just say Subroutines. –“Functions” generally means built-in.
1 An Introduction to Perl Part 1 CSC8304 – Computing Environments for Bioinformatics - Lecture 7.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
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.
Perl By Gabe and Ted. History Perl was created by Larry Wall while working at NASA’s Jet Propulsion Labs. Larry Wall also created patch which is in widespread.
20-753: Fundamentals of Web Programming 1 Lecture 12: Javascript I Fundamentals of Web Programming Lecture 12: Introduction to Javascript.
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.
Conditional Execution
Perl Practical(?)‏ Extraction and Report Language.
Introduction to C Programming Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010 Fall.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Controlling Execution Dong Shao, Nanjing Unviersity.
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.
Perl: Lecture 1 The language. What Perl is Merger of Unix tools – Very popular under UNIX – shell, sed, awk Programming language – C syntax Scripting.
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.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
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
CS 105 Perl: Data Types Nathan Clement 15 May 2014.
Introduction to Perl “Practical Extraction and Report Language” “Pathologically Eclectic Rubbish Lister”
CS 330 Programming Languages 10 / 02 / 2007 Instructor: Michael Eckmann.
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.
Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004.
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.
Introduction to Perl NICOLE VECERE. Background General Purpose Language ◦ Procedural, Functional, and Object-oriented Developed for text manipulation.
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.
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
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.
Operators. Perl has MANY operators. –Covered in Chapter 3 of Camel –perldoc perlop Many operators have numeric and string version –remember Perl will.
CS 330 Programming Languages 09 / 30 / 2008 Instructor: Michael Eckmann.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
Control Structures: if Conditional
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
Control Structures: for & while Loops
Context.
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
CISC124 Labs start this week in JEFF 155. Fall 2018
PowerShell Flow of Control Copyright © 2016 – Curt Hill.
INTRODUCTION to PERL PART 1.
Presentation transcript:

CS 105 Perl: Basic I/O, Context, Strings, Lists Nathan Clement January 22, 2014

Agenda Today we will cover Basic I/O Context String literals and quoting Lists Intermediate iteration – foreach – Array iteration – Hash iteration given / when

Survey Results Languages Known – “C – I know some, I’ll use it if I want total control.” Workload – “Should be easy.” – “It’s like a 3 hour class for 1 hour of credit.” – “The workload will be more intense as the semester progresses but overall the class will be a good experience.”

if with else if ($rich) { print "I am the 1\%\n"; } elsif ($poor) { print "I’m economically disadvantaged\n"; } else { print "I’m disappearing!!\n"; } How to handle the age-old “Dangling Else” problem

while loop A simple while loop (review): while ($a > 0) { print $a." bottles of beer.\n"; $a--; } Do any questions come to mind?

Numeric vs. Stringwise Comparisons Perl has two sets of operators depending on if you want to compare two scalars numerically or as strings. OperatorNumericStringwise Less than <lt Less than or equal to <=le Equal to ==eq Greater than >gt Greater than or equal to >=ge Not equal !=ne

Basic Input/Output One way to read lines from standard input: while (defined($a = )) { chomp($a); # do something with $a } STDIN is the built-in filehandle for standard input. Placing a filehandle in the angle brackets ( ) tells Perl to return the next line from that file. When the end-of-file is reached, will return undef. Removes line terminator

Our own wc –l Increment a value for each line read from STDIN. while (defined($a = )) { $b++; } print $b. "\n";

Context Perl has several contexts that affect how a value is used. Scalar – Numeric – String – Boolean – don’t care List Void Interpolative Perl will perform a default conversion, if necessary, of a value into the desired context. Context only affects evaluation; it does not change the values stored in variables.

Numeric Context A numeric operation wants a number, so the value is evaluated in numeric context. $b = "10"; $a += $b; We initialized $b as a string, but Perl will automatically convert it to a number because the + operator forces a numeric context. Perl will even convert numbers into integers (by rounding) if the specific operation requires an integer (e.g. modulus, % )

String Context Similarly, a string operation wants a string, so its inputs have string context. $a = "Fingers: "; $b = 10; $a.= $b; We initialized $b as a number, but Perl will transparently convert it into a string because the. operator forces a string context. Remember, the numeric value stored in $b does not change.

undef awakening In a string context, undef becomes the empty string. In a numeric context, undef becomes 0. In a boolean context, undef needs no conversion: it’s already considered false. In fact, boolean context will never convert anything, since it applies to numbers, strings, lists, and undefined values.

String Literals Recall from earlier this lecture: print $a. " bottles of beer on the wall.\n"; # we could have done this: print "$a bottles of beer on the wall.\n"; # the result is the same Values placed in a double-quoted string are evaluated in interpolative context.

Interpolation interpolate, v. 1. to introduce (something additional or extraneous) between other things or parts; interject; interpose; intercalate. Basic interpolation rules: scalar values are evaluated in string context – escape them with \ to prevent this escape sequences can be used for control characters – \n for newline – \r for carriage return – \t for (horizontal) tab – there are many others

Single quotes Don’t want interpolation? Use single quotes. if ($a) { print '$a is true', "\n"; } Single quotes do not interpolate variables or escape sequences. We could escape the $ with a backslash. if ($a) { print "\$a is true\n"; }

Perl style: use interpolation! Recall from earlier this lecture: print $a. " bottles of beer.\n"; # What a newbie... print "$a bottles of beer.\n"; # Much better! Please write your code as in the second example.

Lists Lists allow us to initialize arrays and = (1, 2, 3, = ('a', 'b', 'c', 'd');

Lists save typing Lists are much better than initializing each element = (1, 2, 3, 4); is equivalent to $a[0] = 1; $a[1] = 2; $a[2] = 3; $a[3] = 4;

Lists and Hashes Lists can also be used to initialize hashes. %a = ('a', 1, 'b', 2); is equivalent to undef %a; $a{'a'} = 1; $a{'b'} = 2;

The fat arrow: => The => operator is like a comma in almost every way... %a = (a => 1, b => 2); except that the argument to its left will be treated as a string if it is a bareword. A bareword is an identifier without a sigil. So far, only keywords and some operators ( eq, etc.) are allowed to be used without quotes or sigils. In this example, a and b are barewords but are evaluated as strings because of the => operator. The end result is the same as the previous slide.

Perl style: use the fat arrow! The proper, idiomatic thing to do in Perl is to use => when the two delimited elements are pairs. It can be used anywhere a comma could be used. I only gave the previous example with commas to drive home the point that commas are the standard (not fancy) separator. Fat arrow is a fancy comma.

Barewords in hash keys The same bareword-to-string promotion also happens inside the curly braces of a hash key. $a{a} = 1; $a{b} = 2;

Hashes are unordered Remember: hashes are unordered. The following two lines are equivalent: %a = (a => 1, b => 2); %a = (b => 2, a => 1);

foreach iteration You will iterate over arrays a lot in Perl. For general loops over arrays, use foreach. foreach is intended to be dwimmy. For example: foreach $foo { $foo.= $foo; } You would read this as “for each foo in array foo...”

foreach iteration over hashes You can also use foreach, to iterate over hashes. For general loops over hashes, use foreach over the keys of the hash. foreach $foo (keys %foo) { $foo{$foo}.= $foo; } You would read this as “for each foo that is a key in hash foo...”

foreach iteration over hash values While considerably less common or useful, you can also look at just the values in a hash. foreach $bar (values %foo) { print "$bar\n"; } This reads “for each bar that is a value in hash foo...”

foreach vs. for Perl also has a for loop with syntax similar to C and Java. It will not be covered in this class since you should already be an expert in its use.

foreach, for, whatever Actually, foreach and for are synonyms. Perl can figure out which type of loop you mean, so the two keywords are interchangeable. Using the for keyword for “foreach-style” loops is okay. for $baz { #... }

given and when Perl 5.10 finally introduces a switch/case mechanic into Perl. given plays the part of switch, and when plays the part of case. use feature qw(switch); given ($grade) { when (’A’) { print "Excellent\n"; } when (’B’) { print "Good job\n"; } when (’C’) { print "Be all that you can be\n"; } #... }

given / when is ‘smart’ If the when expression is a string, Perl will automatically do a string comparison ( eq ). If it’s a number, Perl will automatically do a numeric comparison ( == = (’0’, ’00’, 0); foreach $a { given ($a) { when (’0’) { print "String-wise equal to ’0’\n"; } when (0) { print "Numerically equal to 0\n"; } } } Perl tests each when clause in turn; the first to match gets executed, even if multiple tests would match. Try changing the order in the example.

The default clause If you would like a default behavior if none of the when clauses match, then use the default clause. given ($grade) { when (’A’) { print "Excellent\n"; } default { print "Too bad...\n"; } } Remember that the clauses are tested in order, so always put default last.

Enabling features As the previous examples have shown, a little bit of effort is required to enable given / when. # loads all Perl 5.10 features # (also includes say, smart match, and more) use feature ’:5.10’; Alternatively, you can just require a version of Perl >= , and the feature pragma will be loaded implicitly. use v5.10; # implicitly does: # use feature ’:5.10’; I prefer this method over the others.