Topic 2: Working with scalars CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 2, pages 19-38, 128-138 Programming Perl 3rd edition chapter.

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

Scalar Data Types and Basic I/O
CIS 240 Introduction to UNIX Instructor: Sue Sampson.
Programming Perls* Objective: To introduce students to the perl language. –Perl is a language for getting your job done. –Making Easy Things Easy & Hard.
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.
Programming and Perl for Bioinformatics Part I. A Taste of Perl: print a message perltaste.pl: Greet the entire world. #!/usr/bin/perl #greet the entire.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
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.
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
Perl Basics Software Tools. Slide 2 Control Flow l Perl has several control flow statements: n if n while n for n unless n until n do while n do until.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Perl Basics Learning Objectives: 1. To understand the commands available for control flow in Perl 2. To learn some useful operators in Perl.
Perl Lecture #1 Scripting Languages Fall Perl Practical Extraction and Report Language -created by Larry Wall -- mid – 1980’s –needed a quick language.
Introduction to Perl Software Tools. Slide 2 Introduction to Perl l Perl is a scripting language that makes manipulation of text, files, and processes.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
1 An Introduction to Perl Part 1 CSC8304 – Computing Environments for Bioinformatics - Lecture 7.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
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.
Perl Practical(?)‏ Extraction and Report Language.
Perl: Lecture 1 The language. What Perl is Merger of Unix tools – Very popular under UNIX – shell, sed, awk Programming language – C syntax Scripting.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
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.
Writing Scripts Hadi Otrok COEN 346.
JavaScript, Fourth Edition
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83,
CS 105 Perl: Basic I/O, Context, Strings, Lists Nathan Clement January 22, 2014.
Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004.
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.
Introduction to Perl NICOLE VECERE. Background General Purpose Language ◦ Procedural, Functional, and Object-oriented Developed for text manipulation.
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
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.
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.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Computer Programming for Biologists Class 4 Nov 14 th, 2014 Karsten Hokamp
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
PERL By C. Shing ITEC Dept Radford University. Objectives Understand the history Understand constants and variables Understand operators Understand control.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
File Handle and conditional Lecture 2. File Handling The Files associated with Perl are often text files: e.g. text1.txt Files need to be “opened for.
Perl Chapter 3 Conditional statements. Control Expressions Control expressions – interpreted as T/F (evaluated as strings or numbers) – simple, relational,
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.
Perl Subroutines User Input Perl on linux Forks and Pipes.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
Chapter 5 - Control Structures: Part 2
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
Control Structures: if Conditional
Chapter 8 JavaScript: Control Statements, Part 2
Control Structures: for & while Loops
Context.
Programming Perls* Objective: To introduce students to the perl language. Perl is a language for getting your job done. Making Easy Things Easy & Hard.
CSC215 Lecture Control Flow.
Perl Control Flow Learning Objectives:
Chap 7. Advanced Control Statements in Java
CSC215 Lecture Control Flow.
INTRODUCTION to PERL PART 1.
Karan Thaker CS 265 Section 001
Presentation transcript:

Topic 2: Working with scalars CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 2, pages 19-38, Programming Perl 3rd edition chapter 2, pages 6-8, 58-67,

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 2 In this topic  Scalar values ► numbers ► strings –string interpolation  defined and undefined values  Scalar variables  Scalar operators and functions  Console input/output ► printing to the screen ► reading from the keyboard  if and while  Scalar values ► numbers ► strings –string interpolation  defined and undefined values  Scalar variables  Scalar operators and functions  Console input/output ► printing to the screen ► reading from the keyboard  if and while

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 3 Scalar values  numbers ► double-precision floating-point (C double) ► e.g., 87, -1.06E20, 0  strings ► basic data type, not an array of char ► arbitrary length, can contain ‘\0’ ► no pointers needed  undefined value ► undef  references ► covered in topic 11  numbers ► double-precision floating-point (C double) ► e.g., 87, -1.06E20, 0  strings ► basic data type, not an array of char ► arbitrary length, can contain ‘\0’ ► no pointers needed  undefined value ► undef  references ► covered in topic 11 Llama3 pages 19-20, 22-23

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 4 Scalar variables  Scalar values are stored in scalar variables  Variables are global by default  All Perl scalar variables begin with $ character ► $apples ► $text2 ► $_  Perl doesn’t usually care if a scalar contains a number or string ► numbers and strings are converted as needed  Scalar values are stored in scalar variables  Variables are global by default  All Perl scalar variables begin with $ character ► $apples ► $text2 ► $_  Perl doesn’t usually care if a scalar contains a number or string ► numbers and strings are converted as needed

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 5 Scalar operators  Most familiar numeric operators available ► +, -, ++, %, &, etc. ► = (assignment), +=, *=, etc. ► / (floating-point division) ►, >=, ==, != (numeric comparison) ► ** (exponentiation)  New string operators ►. (join two strings) –" cat ". " fish " (produces " catfish " ) ► lt, le, gt, ge, eq, ne (string comparison)  Most familiar numeric operators available ► +, -, ++, %, &, etc. ► = (assignment), +=, *=, etc. ► / (floating-point division) ►, >=, ==, != (numeric comparison) ► ** (exponentiation)  New string operators ►. (join two strings) –" cat ". " fish " (produces " catfish " ) ► lt, le, gt, ge, eq, ne (string comparison) Llama3 pages 22,24,25; Camel3 pages , perlop manpage

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 6 Scalar operators  Both > and gt test for “greater than” in scalars ► > compares numbers –and forces both sides into numbers ► gt compares strings –and forces both sides into strings  7 > 30 is false (zero) ► numerically, 7 isn’t greater than 30  7 gt 30 is true (non-zero) ► alphabetically, "7" comes after "30" ► absence of quotes is irrelevant because Perl converts numbers and strings when needed  This forcing of types is related to context ► Topic 3  Both > and gt test for “greater than” in scalars ► > compares numbers –and forces both sides into numbers ► gt compares strings –and forces both sides into strings  7 > 30 is false (zero) ► numerically, 7 isn’t greater than 30  7 gt 30 is true (non-zero) ► alphabetically, "7" comes after "30" ► absence of quotes is irrelevant because Perl converts numbers and strings when needed  This forcing of types is related to context ► Topic 3

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 7 String literals  Perl provides several ways to write a literal string ► depending on your needs  Double quotes ► "blah"  Single quotes ► 'blah'  “Here document” ► <<END multiline text blah END  Perl provides several ways to write a literal string ► depending on your needs  Double quotes ► "blah"  Single quotes ► 'blah'  “Here document” ► <<END multiline text blah END

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 8 String literals  Single-quote delimited ► all characters within string are literal, except –\' (becomes ' ) –\\ (becomes \ ) ► does not interpolate variables ► 'hello' (hello) ► '$35.40' ($35.40) ► 'it\'s' (it's) ► '\n' (backslash followed by n)  Single-quote delimited ► all characters within string are literal, except –\' (becomes ' ) –\\ (becomes \ ) ► does not interpolate variables ► 'hello' (hello) ► '$35.40' ($35.40) ► 'it\'s' (it's) ► '\n' (backslash followed by n) Llama3 page 23; Camel3 pages 60-64

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 9 String literals  Double-quote delimited ► usual C backslash rules (e.g., \n ) apply ► "hello" (hello) ► "it's \$35.40" (it's $34.50) ► "\n" (newline character) ► interpolates scalar and array variables –"hello $name" (becomes hello Fred if $name contains Fred )  Double-quote delimited ► usual C backslash rules (e.g., \n ) apply ► "hello" (hello) ► "it's \$35.40" (it's $34.50) ► "\n" (newline character) ► interpolates scalar and array variables –"hello $name" (becomes hello Fred if $name contains Fred ) Llama3 pages 23-24; Camel3 pages 60-63

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 10 String interpolation  In C, use printf or sprintf to insert variable values into string ► printf("The sum is %d\n", total); ► this works in Perl too  In Perl, can place variable name inside double- quoted string ► print "The sum is $total\n"; ► Perl substitutes current value of $total into the string  Can also use string concatenation operator ► print "The sum is ". $total. "\n";  In C, use printf or sprintf to insert variable values into string ► printf("The sum is %d\n", total); ► this works in Perl too  In Perl, can place variable name inside double- quoted string ► print "The sum is $total\n"; ► Perl substitutes current value of $total into the string  Can also use string concatenation operator ► print "The sum is ". $total. "\n"; Llama3 pages 30-31; Camel3 pages 62-63

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 11 String interpolation  Single-quoted strings do not interpolate ► print 'the sum is $total\n' prints “the sum is $total\n”  If variable name is ambiguous, use braces ► want to print “Today is the 6th” when $day is 6 ► print "Today is the $dayth\n"; –wrong, what is $dayth ? ► print "Today is the ${day}th\n"; –right, uses $day  Can always use braces like this in any situation ► see Topic 11 for further use of this in nested data structures  Single-quoted strings do not interpolate ► print 'the sum is $total\n' prints “the sum is $total\n”  If variable name is ambiguous, use braces ► want to print “Today is the 6th” when $day is 6 ► print "Today is the $dayth\n"; –wrong, what is $dayth ? ► print "Today is the ${day}th\n"; –right, uses $day  Can always use braces like this in any situation ► see Topic 11 for further use of this in nested data structures

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 12 Undefined value  undef ► $x = undef; ► this is the only undefined value  Neither number nor string ► converted to empty string ("") in string context ► converted to zero in numeric context  Used to indicate when a scalar doesn’t have a value ► unassigned scalar variables return undef ► similar uses to NULL in C ► returned by some functions and operators on out-of-range input – returns undef at end of file  use defined function to test an expression ► if (defined $var) {... }  undef ► $x = undef; ► this is the only undefined value  Neither number nor string ► converted to empty string ("") in string context ► converted to zero in numeric context  Used to indicate when a scalar doesn’t have a value ► unassigned scalar variables return undef ► similar uses to NULL in C ► returned by some functions and operators on out-of-range input – returns undef at end of file  use defined function to test an expression ► if (defined $var) {... } Llama3 pages 37-38; Camel3 pages

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 13 Some scalar functions  chomp $string ► removes a newline from the end of $string, if any  length $string ► returns length of $string in characters  uc $string ► returns a version of $string entirely in uppercase ► also lc (lower case)  rand $number ► returns pseudorandom number from 0 to $number  substr $string, $start, $length ► returns substring of $string, starting at $start (zero origin) for $length characters  And many more  chomp $string ► removes a newline from the end of $string, if any  length $string ► returns length of $string in characters  uc $string ► returns a version of $string entirely in uppercase ► also lc (lower case)  rand $number ► returns pseudorandom number from 0 to $number  substr $string, $start, $length ► returns substring of $string, starting at $start (zero origin) for $length characters  And many more Camel3 chapter 29, pages ; perlfunc manpage

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 14 Input and output  Output to screen with ► print function ► printf function ► print "testing\n";  Input from keyboard with ► operator ► reads and returns one line (including newline) from standard input ► $line = ; ► chomp function can be used to remove newline  Output to screen with ► print function ► printf function ► print "testing\n";  Input from keyboard with ► operator ► reads and returns one line (including newline) from standard input ► $line = ; ► chomp function can be used to remove newline Llama3 pages 29-30, 35-36; Camel3 pages 80-83

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 15 Timeout #!/usr/bin/perl -w # Set $pi. $pi = ; # Read a number from the user. print "Please enter radius: "; $radius = ; # Remove the newline from $radius. chomp $radius; # Calculate the circumference. $around = $radius * 2 * $pi; # Print the result. print "The circumference is $around.\n"; #!/usr/bin/perl -w # Set $pi. $pi = ; # Read a number from the user. print "Please enter radius: "; $radius = ; # Remove the newline from $radius. chomp $radius; # Calculate the circumference. $around = $radius * 2 * $pi; # Print the result. print "The circumference is $around.\n";

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 16 Boolean truth  All Boolean conditions evaluated in scalar context  False values are ► undef (the undefined value) ► "" (the empty string) ► 0 (number) and "0" (string)  True values are ► everything else  All Boolean conditions evaluated in scalar context  False values are ► undef (the undefined value) ► "" (the empty string) ► 0 (number) and "0" (string)  True values are ► everything else Llama3 pages 34-35; Camel3 page 29-30; perldata manpage

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 17 if / else statement if (condition) { # These lines execute if condition is true. } elsif (condition2) { # These lines execute if condition2 is true. } else { # These lines execute # if all conditions are false. } Llama3 pages 34-35, 132,133; Camel3 pages ; perlsyn manpage condition evaluated in scalar context zero or more elsif clauses else clause optional all braces are compulsory, unlike C/Java

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 18 Timeout #!/usr/bin/perl -w # Read two numbers. print "Enter a number: "; chomp ($num1 = ); print "Enter another number: "; chomp ($num2 = ); # Calculate the bigger value. if ($num1 > $num2) { $max = $num1; } else { $max = $num2; } # Print result. print "Maximum is $max\n"; #!/usr/bin/perl -w # Read two numbers. print "Enter a number: "; chomp ($num1 = ); print "Enter another number: "; chomp ($num2 = ); # Calculate the bigger value. if ($num1 > $num2) { $max = $num1; } else { $max = $num2; } # Print result. print "Maximum is $max\n";

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 19 while statement while (condition) { # This code executed until condition is false. # Block is never entered if condition was # always false. } Llama3 pages 34-35, , 132,133; Camel3 pages , 701; perlsyn manpage condition evaluated in scalar context all braces are compulsory do {... } while (condition) (post-tested) also exists, as in C/Java

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 20 Timeout # A primitive version of Unix cat program # Read lines from standard input. # returns the next line of input # if there is one, or undef if at end of file. # Test using defined() to see when to stop. while (defined ($line = )) { # Print out the line just read. print $line; } # A primitive version of Unix cat program # Read lines from standard input. # returns the next line of input # if there is one, or undef if at end of file. # Test using defined() to see when to stop. while (defined ($line = )) { # Print out the line just read. print $line; }

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 21 unless and until  Sometimes more natural to express condition as negative ► unless (condition) same as if (!condition) ► until (condition) same as while (!condition)  Sometimes more natural to express condition as negative ► unless (condition) same as if (!condition) ► until (condition) same as while (!condition) Llama3 pages ; Camel3 pages

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 22 Loop control commands  Perl has commands which can alter flow within loop  last ► exits the innermost containing loop ► like C/Java break statement  next ► jumps to end of innermost containing loop –with for loop, executes the increment code ► re-tests loop condition, then continues from beginning of loop ► like C/Java continue statement  redo ► jumps to start of innermost containing loop ► does not re-test loop condition ► no equivalent in C without goto  Perl has commands which can alter flow within loop  last ► exits the innermost containing loop ► like C/Java break statement  next ► jumps to end of innermost containing loop –with for loop, executes the increment code ► re-tests loop condition, then continues from beginning of loop ► like C/Java continue statement  redo ► jumps to start of innermost containing loop ► does not re-test loop condition ► no equivalent in C without goto Llama3 pages ; Camel3 pages ; perlsyn manpage

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 23 Timeout # Print the header of an message. # Mail messages come in two parts: the header and # the body. The first blank line in the message # separates the header from the body. # Read each line. while (defined ($line = )) { # If line is blank (contains only a newline) # then exit the while loop. if ($line eq "\n") { last; } print $line; } # Print the header of an message. # Mail messages come in two parts: the header and # the body. The first blank line in the message # separates the header from the body. # Read each line. while (defined ($line = )) { # If line is blank (contains only a newline) # then exit the while loop. if ($line eq "\n") { last; } print $line; }

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 24 Covered in this topic  Scalar values ► numbers ► strings –string interpolation  defined and undefined values  Scalar variables  Scalar operators and functions  Console input/output ► printing to the screen with print ► reading from the keyboard with  if and while ► unless and until  Scalar values ► numbers ► strings –string interpolation  defined and undefined values  Scalar variables  Scalar operators and functions  Console input/output ► printing to the screen with print ► reading from the keyboard with  if and while ► unless and until

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 25 Going further  References ► the “other kind” of scalar value ► Topic 11  Unicode ► support for national character sets ► Camel3 pages  Operator overloading ► providing new behaviour for built-in operators ► Camel3 pages  Loops, blocks and goto ► putting labels on blocks to change last, next and redo ► more scary things to do with control structures, including implementing C’s switch ► Camel3 pages  References ► the “other kind” of scalar value ► Topic 11  Unicode ► support for national character sets ► Camel3 pages  Operator overloading ► providing new behaviour for built-in operators ► Camel3 pages  Loops, blocks and goto ► putting labels on blocks to change last, next and redo ► more scary things to do with control structures, including implementing C’s switch ► Camel3 pages

Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 26 Next topic  Lists  Arrays  for and foreach  Context  Lists  Arrays  for and foreach  Context Llama3 chapter 3 Camel3 pages 69-76, perldata manpage