CPTG286K Programming

Download Report

Transcript CPTG286K Programming

CPTG286K Programming - Perl
Chapter 2: Scalar Data
Scalar Data
• In PERL, numbers and strings are scalar
data, and are used interchangeably
• Operators act on scalar data, which yield a
scalar result
• Scalar values can be stored in scalar
variables
• Scalar data can be written to and read from
files and devices
Numbers
• PERL uses double-precision floating-point values
to store integers AND floating point numbers
• Literals are values used in the source code (as
opposed to those read from keyboard or files)
• Float literals can contain decimal points, or use E
(exponential) notation
• Integer literals do not contain decimals, and do not
start with 0; octal and hexadecimal numbers start
with 0
Example of Numbers
1.25
7.25e45
-12e-24
-2004
0377
-0xff
#
#
#
#
#
#
about 1 and a quarter
7.25 x 10 to the 45th power
negative 12 x 10 to the –24th power
negative integer
377 octal, or 255 decimal
negative FF hex, or –255 decimal
Strings
• Strings are a sequence of characters from
the entire 256 character set (includes NUL)
• Shortest string has no characters; longest
string fills all available memory
• Literal strings can be single-quoted or
double-quoted
Note: Back-quoted and here strings are covered in chapters
14 and 19
Single-quoted strings
• Only characters between single-quotes are part of
the string
• Exception: The backslash can be used to force
display of single-quote and backslash:
‘don\’t’
‘silly\\me’
‘hello\n’
‘hello
there’
# d, o, n, single-quote, t
# silly, backslash, me
# hello, backslash, n
# hello, newline, there
Double-quoted strings
• Double-quoted strings allow the backslash to
specify any character
“hello world\n”
“new \177”
“coke\tsprite”
# hello world, newline
# new, space, delete (octal 177)
# coke, tab, sprite
• Variable interpolation allows values from scalar
and array variables to appear in double-quoted
strings:
print “Hello, $name\n”;
# $name = ‘Randal’;
Scalar Operators
• Operators (such as +), take one or more
operands (such as 5 and 6), to produce a
new result (such as 11)
• Operators act on both numbers and strings
• Numeric and string comparison operators
can both be used for strings
• Common precedence rules govern PERL
operators
Use of Numeric Operators
2+3
5.1-2.4
3*12
14 / 2
2**3
10%3
#
#
#
#
#
#
2 + 3 = 5
5.1 - 2.4, approx. 2.7
3 x 12 = 36
14 / 2 = 7
2 to the 3rd power
Remainder of 10 / 3 = 1
String Operators
• Numeric and string comparison operators
(return true or false):
Comparison
Equal
Not equal
Less than
Greater than
Less than or equal to
Greater than or equal to
Numeric
==
!=
<
>
<=
>=
String
eq
ne
lt
gt
le
ge
• The . operator is used to concatenate strings
String Operators (Cont’d)
• The x operator is used to make as many
concatenated copies of a string indicated by
a numeric operand to its right:
“fred”x3
# is “fredfredfred”
“barney”x(3+1) # is “barney” x 4, or
# “barneybarneybarneybarney”
(3+2)x4
# is 5 x 4, “5” x 4, or “5555”
Precedence and Associativity
• PERL uses common mathematical precedence
rules: 2+3*4 is 2+(3*4) = 14
• When two operators of same precedence compete
for three operands, associativity resolves the order
of operations:
Associativity
Right
Left
Thus:
2 ** 3 ** 4
30 / 6 * 3
Operator
(refer to Table 2-3)
** (exponentiation)
* / % x (multiply, divide, modulus, str. repeat)
# 2 ** (3**4), or 2 ** 81, approx 2.41e24
# (30/6) * 3 = 15
Automatic number conversion
• When a string value is used as an operand
for a numeric operator, PERL converts the
string value to a numeric value:
100 + “ 23.45fred”
100 + “fred”
# is 123.45
# is 100
Automatic string conversion
• When a numeric value is used as an operand
for a string operator, PERL converts the
numeric value to a string value:
“X”.(4*5)
# same as “X”.20 or “X20”
Scalar Variables
• Scalar variables can hold a number, string, or
reference. Before they are first assigned they
contain the undef value
• Names start with a $ sign followed by up to 255
characters (letters, digits, underscores)
• Upper- and lowercase letters are distinct: $a is not
the same variable as $A
• Use descriptive variable names instead of
ambiguous variable names: $line_number is
better than $ln
Scalar Assignment Operators
• Besides common assignment operations, the
following are also valid:
$b = 4+($a = 3);
$d = ($c = 5);
$d = $c = 5;
#
#
#
#
#
#
assign 3 to $a, then add 4 to
$a, so $b is 7
copy 5 into $c, and then also
into $d
same as above, due to right
associativity
Binary Assignment
• A shorthand for expressions where the same
variable appears on both sides of the
assignment.
$a += 5;
$b *= 3;
$str .= “ “;
$a **= 3;
#
#
#
#
same
same
same
same
as
as
as
as
$a =
$b =
$str
$a =
$a + 5;
$b * 3;
= $str . “ ”;
$a ** 3;
Auto- increment/decrement
++$a;
--$a;
# same as $a += 1;
# same as $a -= 1;
• Auto increment and decrement can use prefix and suffix
forms
• Prefix form:
$d = 17;
$e = ++$d;
# $e and $d are both 18
• Suffix form:
$c = 17;
$d = $c++;
# $d is 17, but $c is 18
The chop function
• chop removes the last character from the
string value of a scalar variable
$a = “hello world\n”;
chop $a;
# $a is now “hello world”
chop $a;
# $a is now “hello worl”
• If chop is given an empty string, it does
nothing, and returns nothing, and gives no
error (unless the –w switch is used)
The chomp function
• The chomp operator is safer to use, as it
only removes the newline character (or
whatever the $/ record separator is set to)
$a = “hello world\n”;
chomp $a;
# $a is now “hello world”
chomp $a;
# $a still “hello world”
chomp and <STDIN>
• The standard input or <STDIN> can be used as a
scalar value for keyboard input, which contains
the newline character.
• <STDIN> returns undef if there are no more lines
to read (i.e. someone pressed CTRL-D)
• Typical input sequence:
$a = <STDIN>;
chomp($a);
# get text
# remove newline
• Common abbreviated input sequence:
chomp($a = <STDIN>); # must use ()
Scalar Interpolation into Strings
• Double-quoted string literals are scanned
for scalar variable names. If a variable
reference is found, the scalar variable name
is replaced with its current value
• The text that replaces the variable is not rescanned:
$x = ‘$fred’;
$y = “hey $x”;
# a dollar sign followed by “fred”
# $y is ‘hey $fred’: not re-scanned
Scalar Interpolation into Strings (Cont’d)
• Substitutions can be prevented by using
single quotes with concatenation operator,
or backslashes
• Curly brackets can be used to specify
variable delimiters for ambiguous long
variable names
• Use case-shifting escapes (\l, \L, \u, \U) to
alter case of letters in variable interpolation
Interpolation Examples
$a
$b
$x
$y
=
=
=
=
“fred”;
“some text $a”;
‘$fred’;
“hey $x”;
#
#
#
#
$b is “some text fred”
$x is literally $fred
value is ‘hey $fred’:
no double substitution
$fred = ‘hi’;
$barney = “a test of ” . ’$fred’;
# ‘a test of $fred’
$barney2 = “a test of \$fred”;
# same thing
More Interpolation Examples
$fred = “pay”;
$fredday = “wrong!”;
$barney = “It’s $fredday”;
$barney = “It’s ${fred}day”;
$barney = “It’s $fred”.“day”;
$barney = “It’s ” . $fred . “day”;
$fred = “fred”;
$bigfred = “\Ufred”;
$capfred = “\u$fred”;
$barney = “\LBARNEY”;
$capbarney = “\u\LBARNEY”;
#
#
#
#
#
#
#
#
“It’s wrong!”
“It’s payday”
Same thing
Same thing
$bigfred is “FRED”
$capfred is “Fred”
$barney is “barney”
$capbarney is “Barney”