Scalar Data Types and Basic I/O. Variables in Perl You DO NOT have to declare variables in Perl....

23
Scalar Data Types and Basic I/O

Transcript of Scalar Data Types and Basic I/O. Variables in Perl You DO NOT have to declare variables in Perl....

Scalar Data Types and Basic I/O

Variables in Perl

• You DO NOT have to declare variables in Perl.– Unless you force it to force you to declare

variables.

• Three basic types of variables:– Scalar– Array– Hashes

Scalars

• Scalar variables store “single values”.• This “single value” can be any of the

following types:– int, float, double, char, string, or references.

• In Perl these various types fall into one of three categories:– numbers, strings, and references.

• You don’t have to declare a variable’s type.

Scalars: Declaration

• All scalar variables begin with a $.– $ is NOT part of the variable!

• Next character is either a letter or ‘_’.

• Remaining characters are a mix of letters, numbers, and ‘_’.

• Correct: $x, $myvar123, $avg_height

• Wrong: $2values, $avg-height, $good$day.

Scalars: Numbers

• Unlike C/C++, all numeric data in Perl are stored as double precision floating points.– Ex: 37 3.7 .37 37. 3E7 3e7 3E-7– Hex: 0x2aff, 0xAA3, 0XFFF– Octal: 077 0276– Underscore: 3_212_567 → 3,212,567.

• Again, you do not need to specify the type.

Numeric Operators

Operator Associativity

++ -- none

unary - right

** right

* / % left

binary + - left

++ and – have the highest precedence.

Examples

• 4 % 2 → 0• 5 / 2 → 2.5 (5 and 2 are coerced from integers to

reals).• $total++ * 3 • $a ** 2• $b / $ c / 2• Important. The order of evaluation of operands

of operators is unspecified. This is left for the compiler to decide.– Ex: $x++ * $x--

Scalars: Strings

• Unlike C/C++, strings in Perl are not terminated by ‘\0’.

• They are not represented as an array of characters.– Individual characters cannot be accessed with

[ ].

• There are two types of strings in Perl– Single quoted strings (‘).– Double quoted strings (“).

Single Quoted Strings

• Strings delimited by (‘). They are not interpolated and cannot contain escape sequence characters.

• Examples:– ‘hello’– ‘Don\’t do it!’– ‘can\’t, won\’t, wouldn\’t ever!’– ‘apples are good\n’ ??

Single Quoted Strings

• Another to say the same thing:– q^hello^– q^apples are good\t^– q^Don’t do it!^– q^can’t, won’t, wouldn’t ever!^

• Can also use ( ), { }, [ ], < > for better readability:– Q(hello)– Q{can’t, won’t, wouldn’t ever!}

Double Quoted Strings.• Differs from single quoted strings in two ways:

– Can include escape sequence characters – e.g. \n, \t, \r, etc.– Variables in the string are interpolated.

• Examples:– “The man said, \”Quantity \t Price \t Total\” \n\n”– “Apples are good for $name.”

→ “Apples are good for bob.”– “Apples are good for \$name.”

→ “Apples are good for $name.”– “Today is ${day}day.”

→ “Today is Monday.”

• Can also use qq– Ex: qq*”No way!”, said the girl.*

When q Meets qq

• What happens when you put (‘) and (“) together?

• If “ is embedded within ‘– ‘The boy said, “Today is $day” ’

• If ‘ is embedded within “– “The boy said, ‘Today is $day’ “

String Operators

• String Catenation (.) Append two strings together.– “Happy” . “ Birthday” → “Happy Birthday.”– $str . “ Holidays” → “Happy Holidays.”– The operands are not effected by (.)

• Repetition operator (x)– “Beat OU! ” x 3 → “Beat OU! Beat OU! Beat OU! ”

• What about?– “Happy ” . “Birthday! ” x 2

→ “Happy Birthday! Birthday! ”

String Functions

• Perl provides several useful string manipulation functions.– chop and chomp– length, lc, uc– ord, hex, oct– index, rindex– substr, join

Chop and Chomp

• Chop removes the last character in a string.– chop(“apples”) → “apple”– If $a, $b, and $c are “a”, “an”, and “ant”, then

chop($a, $b, $c) → “” “a” “an”

• Chomp removes the ending input record separator (e.g. newline) in a string.– If string does not end with an input record

separator, then chomp does nothing to the string and returns 0.

length, lc, and uc

• length returns the number of chars.– Ex: length(“apples”) → 6

• lc converts a string to all lower case.– Ex: lc(“ApPlEs”) → “apples”

• uc converts a string to all upper case.– Ex: uc(“apples”) → “APPLES”

index and rindex

• index searches for the starting position of a substring.

• rindex same as index except search is done from right to left.

• Examples:– index(“apples”, “pp”) returns 1– rindex(“apples”, “pp”) returns 1– index(“apples”, “p”) returns 1– rindex(“apples”, “p”) returns 2– index(“apples”, “q”) returns -1

substr

• substr extracts a substring

• The way to call it is:– substr(string, position, length)

• Examples:– substr(“fruit juice”, 0, 3) returns “fru”– substr(“fruit juice”, 3, 5) returns “it ju”– substr(“fruit juice”, -3, 3) returns “ice”

join

• Like (.) but appends several strings separated by a deliminator.

• The way to call it is:– join Expression, List

• Example: $month = “09”, $day = “01”, $year = “05”– join ‘/’, $month, $day, $year → “09/01/05”.– join ‘/’, $month, $day, 2005 → ??

Mixed Modes

• What happens when strings and numbers interact?

• The output depends on the context.• Examples: $str = “32abc”

– 7 + $str– 7 . $str

• What if $str = “abc32”– 7 + $str– 7 . $str

→ 39→ “732abc”

→ 7

Assignments

• Simple assignment operators (=)– $x = 2;– $average = $sum / $total;– $x = $y = $b = 2;– $result = 17 * ($sum = $x + $y);– chomp($str = $str1. $str1);

• Compound assignment operators (<op>=)– $sum += $new_value;– $str .= “ing”;– $result **= 4;

Basic I/O

• <STDIN> reads input from a keyboard– $new_input = <STDIN>

• print writes output to screen– print “Hello world!\n”;– print (“Was summer vacation fun?\n”);– print (“The sum is: $sum”,

“\tThe average is: $average\”);

A Simple Example

# circle

# Input: The radius of a circle.

# Output: The area and circumference of the circle.

$pi = 3.14;

print “Please enter the radius of the circle: ”;

$radius = <STDIN>;

$area = $pi * $radius * $radius;

$circumference = $pi * 2 * $radius;

print “A circle of radius $radius has an area of $area \n”,

“ and a circumference of $circumference \n”;