topic 2: working with scalars cse2395/cse3395 perl programming learning perl 3rd edition chapter 2,...
TRANSCRIPT
Topic 2: Working with scalarsTopic 2: Working with scalars
CSE2395/CSE3395Perl Programming
CSE2395/CSE3395Perl Programming
Learning Perl 3rd edition chapter 2, pages 19-38, 128-138
Programming Perl 3rd edition chapter 2, pages 6-8, 58-67, 114-118
2Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
In this topicIn 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
3Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
Scalar valuesScalar 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
4Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
Scalar variablesScalar 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
5Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
Scalar operatorsScalar 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 86-110, perlop manpage
6Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
Scalar operatorsScalar 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
7Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
String literalsString literals
Perl provides several ways to write a literal string► depending on your needs
Double quotes► "blah"
Single quotes► 'blah'
“Here document”► <<ENDmultiline textblah blahEND
Perl provides several ways to write a literal string► depending on your needs
Double quotes► "blah"
Single quotes► 'blah'
“Here document”► <<ENDmultiline textblah blahEND
8Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
String literalsString 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
9Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
String literalsString 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
10Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
String interpolationString 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
11Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
String interpolationString 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
12Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
Undefined valueUndefined 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
– <STDIN> 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
– <STDIN> returns undef at end of file
use defined function to test an expression► if (defined $var) { ... }
Llama3 pages 37-38; Camel3 pages 818-819
13Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
Some scalar functionsSome 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 677-830; perlfunc manpage
14Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
Input and outputInput and output
Output to screen with► print function► printf function► print "testing\n";
Input from keyboard with► <STDIN> operator► reads and returns one line (including newline) from
standard input► $line = <STDIN>;► chomp function can be used to remove newline
Output to screen with► print function► printf function► print "testing\n";
Input from keyboard with► <STDIN> operator► reads and returns one line (including newline) from
standard input► $line = <STDIN>;► chomp function can be used to remove newline
Llama3 pages 29-30, 35-36; Camel3 pages 80-83
15Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
TimeoutTimeout
#!/usr/bin/perl -w
# Set $pi.$pi = 3.1415926535898;
# Read a number from the user.print "Please enter radius: ";$radius = <STDIN>;# 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 = 3.1415926535898;
# Read a number from the user.print "Please enter radius: ";$radius = <STDIN>;# Remove the newline from $radius.chomp $radius;
# Calculate the circumference.$around = $radius * 2 * $pi;
# Print the result.print "The circumference is $around.\n";
16Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
Boolean truthBoolean 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
17Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
if/else statementif/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 114-115; perlsyn manpage
condition evaluated in scalar context
zero or more elsif clauses
else clause optional
all braces are compulsory, unlike C/Java
18Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
TimeoutTimeout
#!/usr/bin/perl -w
# Read two numbers.print "Enter a number: ";chomp ($num1 = <STDIN>);print "Enter another number: ";chomp ($num2 = <STDIN>);
# 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 = <STDIN>);print "Enter another number: ";chomp ($num2 = <STDIN>);
# Calculate the bigger value.if ($num1 > $num2){ $max = $num1;} else { $max = $num2;}
# Print result.print "Maximum is $max\n";
19Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
while statementwhile statement
while (condition){ # This code executed until condition is false. # Block is never entered if condition was # always false.}
Llama3 pages 34-35, 128-129, 132,133; Camel3 pages 112-115, 701; perlsyn manpage
condition evaluated in scalar context
all braces are compulsory
do { ... } while (condition)(post-tested) also exists, as in C/Java
20Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
TimeoutTimeout
# A primitive version of Unix cat program
# Read lines from standard input.# <STDIN> 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 = <STDIN>)){ # Print out the line just read. print $line;}
# A primitive version of Unix cat program
# Read lines from standard input.# <STDIN> 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 = <STDIN>)){ # Print out the line just read. print $line;}
21Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
unless and untilunless and until
Sometimes more natural to express condition as negative► unless (condition) same asif (!condition)► until (condition) same aswhile (!condition)
Sometimes more natural to express condition as negative► unless (condition) same asif (!condition)► until (condition) same aswhile (!condition)
Llama3 pages 128-130; Camel3 pages 114-116
22Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
Loop control commandsLoop 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 138-142; Camel3 pages 120-123; perlsyn manpage
23Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
TimeoutTimeout
# Print the header of an email 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 = <STDIN>)){ # 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 email 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 = <STDIN>)){ # If line is blank (contains only a newline) # then exit the while loop. if ($line eq "\n") { last; }
print $line;}
24Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
Covered in this topicCovered 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 <STDIN>
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 <STDIN>
if and while► unless and until
25Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
Going furtherGoing further
References► the “other kind” of scalar value► Topic 11
Unicode► support for national character sets► Camel3 pages 401-410
Operator overloading► providing new behaviour for built-in operators► Camel3 pages 347-362
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 123-127
References► the “other kind” of scalar value► Topic 11
Unicode► support for national character sets► Camel3 pages 401-410
Operator overloading► providing new behaviour for built-in operators► Camel3 pages 347-362
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 123-127
26Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University
Next topicNext topic
Lists Arrays for and foreach Context
Lists Arrays for and foreach Context
Llama3 chapter 3Camel3 pages 69-76, 112-120perldata manpage