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