Upload
tutorialsruby
View
738
Download
0
Tags:
Embed Size (px)
DESCRIPTION
Citation preview
Numbers
● Numbers are double precision floating point values (double in C)3, 1.5, 2.7e8, 2_427_132_115,0577, 0xf3ab, 0b1110001011
● Numeric operationsAdd (+), subtract (), negate (), multiply (*), divide (/), modulus (%)3 + 4.2, 2.3e4*6.2523, 10%4
Strings
● Can be any length & can contain any characters● Singlequoted strings'Pablo de Gracia, Jr.''The winter of our discontent.''Queen\'s Jewels'# the single quote ' is specified as \''The backslash \\ is special'# the backslash \ is specified as \\
Strings● Doublequoted strings”against earth's flowing breast”“I am called \”handsome\” by some”“I came.\nI saw.\nI conquered.\n”“Tab\tseparated\tentries\there”
● String concatenation“Hello ” . “world\n”
● String repetition“maganda ” x 3
Autoconversion: Numbers & Strings
● Arithmetic operations (+,,*,/,%) convert strings to numbers“12plus2” + “3” # gives the number 15
● String operation (.) converts numbers to strings“XJW” . 24*5 # gives the string “XJW120”
Variables
● Variable names[$@%][AZaz_][09AZaz_]*
● Scalar variables, name starts with $– Holds one value (scalar value)– Examples:$daily_rate = 350.00;$horse_name = “Heaven's Pride”;$monthly_pay = $daily_rate * 22;
Binary Assignment Operators
● Replace $var = $var op $val;by $var op= $val;
● Examples:$new_rate += 12;$quotient /= 10;$name .= “, PhD”;$balance = $withdrawal;
Output Using “print”
● Write output to stdout using print
print “Hello, world!\n”;print “The answer is ” . 350 * 6 . “\n”;print “The answer is ”, 350 * 6,“\n”;
Interpolation● Interpolation: the replacement of a scalar
variable by its value in a double quoted string or when occuring alone
● Examples$meal = 'beef steak';print “Juan ate $meal\n”;print “I like $meal for dinner\n”;print “Juan's dinner is “ . $meal;print “Juan's dinner is “, $meal;
Delimiting the Variable Name
● Use { } to delimit the variable name to be interpolated
● Examples$what = 'steak';print “I love all kinds of ${what}s\n”;print “I love all kinds of $what”, “s\n”;print “Prime rib is the $what of ${what}s\n”;
Comparison Operators
● Numeric comparison operators==, !=, <, >, <=, >=Examples:50 == 100/2; # true100/3 != 33.3 # true
● String comparison operatorseq, ne, lt, gt, le, ge'pedro' lt 'jose' # false'jose' eq “jose” # true' ' gt ''# true
Boolean Values● undef, number zero (0), string zero ('0'), the
empty string (''), are all false. Undef designates a variable with no value assigned yet.
● nonzero numbers (like 1) and nonempty strings (except '0') are all true.
● Examples$bool1 = 'Fred' lt 'fred';$bool2 = 'fred' lt 'Fred';print $bool1; # prints 1 for trueprint $bool2; # empty string for false
If Control Structure
● Syntaxif( condition ) { truepart; } else { falsepart; }
● Example$disc = $b*$b – 4.0*$a*$c;if( $disc >= 0.0 ) { print “Real roots\n”;} else { print “Complex roots\n”;}
Reading One Line from Stdin
● Use <STDIN> to read one line from standard input, usually the console keyboard
● Examples:print “Enter first name: “;$fname = <STDIN>;print “Enter last name: “;$lname = <STDIN>;chomp($fname);chomp($lname);print “Your name: $fname $lname\n”;
The chomp() Function
● chomp() removes a trailing newline '\n' from the string value of a variable
● Version2 of program:print “Enter first name: “;chomp($fname = <STDIN>);print “Enter last name: “;chomp($lname = <STDIN>);print “Your name: $fname $lname\n”;
While Control Structure● Syntax:
initialization;while ( condition ) { statements; reinitialization;}
● Example:$i = 1;while($i <= 10) { print “Counting $i\n”; ++$i;}
UNDEF
● If an undefined variable is used as a number, undef is like zero (0). If used as a string, undef is like the empty string ('')
● If $x is undefined, the following are allowed:$x += 2;$x .= 'bye';
● If $x has a value, then$x = undef;makes $x undefined
The defined() Function● The <STDIN> operation may return the value
undef when there is no more input, such as at endoffile
● The function defined() can test if <STDIN> read one line of input from standard input.
● Examplewhile(defined($line = <STDIN>)) { print “You typed: $line”;}print “No more input\n”;
Exercises● Write a Perl program that reads lines of input
from <STDIN>, and prints each line read. Stop when the line that is read is 'Done' (without the quotes).
● Write a Perl program that reads the values of three variables $num1, $oper, and $num2 from <STDIN>. If the value of $oper is one of the strings 'plus', 'minus', 'times', or 'over', the program should carry out the indicated operation on $num1 and $num2.
Lists & Arrays
● List: an ordered collection of scalar values. The index is the position of a scalar value in the list. The index runs from 0 to (n1), where n is the size of the list. An array is a variable that contains a list, and starts with a @sign
● Example:@quals@friends
Initializing Arrays with Literal Values● An array may be initialized with values in
parentheses ( ). Example: @propty = ('Pablo', 62, 'male', undef);
Here, the array is @propty, and the values in the list are:$propty[0] is 'Pablo'$propty[1] is 62$propty[2] is 'male'$propty[3] is undef #civil status
Values May All Be Same Type● All list values may be the same type@friends = ('Pablo', 'Jose', 'Juan', 'Mario', 'David');
Here, the array is @friends, and the values in the list are:$friends[0] is 'Pablo'$friends[1] is 'Jose'$friends[2] is 'Juan'$friends[3] is 'Mario'$friends[4] is 'David'
Values of Array Indices● Any value, variable, or expression, whose value is
integer or can be converted to integer can be used as index.
● Example:$ndx = 2.5;$friends[$ndx+1] is $friends[3]
● $#friends is the value of the last index of array @friends, which is 4.
● $friends[$#friends+10] = 'Carlos';adds element 'Carlos' at index 14, the 15th element. Values at index 5 to 13 will be undef.
Initializing Array with Literal Values
● @arr = ( );@arr = (5..10, 17, 21);@arr = ($a..$b);@arr = qw/ Pablo Jose Mario /;@arr = qw! Pablo Jose Mario !;@arr = qw( Pablo Jose Mario );@arr = qw{ Pablo Jose Mario };@arr = qw< Pablo Jose Mario >;
Interpolate Arrays/Values in Strings● If @arr is an array, then array @arr and list
value $arr[k] will be interpolated (evaluated) when placed inside double quoted strings
● Example interpolating arrays@arr = (5..7);print “Four @arr eight\n”;# will print Four 5 6 7 eight
● Example interpolating list values@toy = ('toycar', 'toyrobot', 'toygun');print “I have a $toy[2] at home\n”;
pop( ) Function
● pop() removes the rightmost list value from an array
● Example:@stk = (5..9);$a = pop(@stk);# remove 9 leaving 5..8, $a = 9$b = pop @stk;# remove 8 leaving 5..7, $b = 8pop @stk; # remove 7 leaving 5..6
push() Function
● push(): adds new rightmost values to the list of an array
● Example:@stk = (5..8);push(@stk, 0); # now (5,6,7,8,0)push @stk, (1..3);# now (5,6,7,8,0,1,2,3)@stk2 = qw/ 10 11 12 /;push @stk, @stk2; # now (5,6,7,8,0,1,2,3,10,11,12)
shift() and unshift()
● shift() is like pushing new first values, unshift() is like popping the first value. These operations are done on the leftmost end of the array.
● @stk = (5..9);shift(@stk, 4); # now (4..9)shift @stk, (1..3); # now (1..9)$a = unshift @stk;# remove 1 leaving (2..9), $a = 1
foreach Control Structure
● Syntax: foreach $var (@arr) { body; }● Example: form the pural form of each fruit:@fruits = qw/mango banana durian/;foreach $fr (@fruits) { $fr .= 's';}print “@fruits\n”;
Perl's Default Variable: $_
● If you omit $var in a foreach loop, you can refer to this variable using $_foreach (1..10) { $sum += $_;}print “Total of 1..10 is $sum\n”;
● If you omit $var in a print statement, the value of $_ will be printed.$_ = “Today is Saturday\n”;print;
reverse() and sort()● reverse(@arr) reverses the order of values in
the list@fruits = qw/mango papaya chico/;@revfr = reverse(@fruits);@fruits = reverse(@fruits);
● sort(@arr) sorts the values in the list in increasing lexicographic order, or string order, not numeric order@fruits = qw/mango papaya chico/;@sfruits = sort(@fruits);@rfruits = reverse sort @fruits;
Forcing scalar() Context
● If you want to use an array @arr in a scalar context (for example, get the number of elements in the list), use the function scalar()@fruits = qw/mango banana orange/;print “Favorite fruits: @fruits\n“;print “My favorite fruits are “, scalar(@fruits), “ in all\n”;
<STDIN> as List or Scalar
● $line = <STDIN>;reads one line from <STDIN>
● @lines = <STDIN>;reads the entire file <STDIN> until endoffile and assigns each line as an element of the array @lines. If file is big, @lines may use up a huge amount of memory. The endoffile of <STDIN> is indicated by typing ControlD in Unix.
Sorting Lines from <STDIN>
● chomp(@lines = <STDIN>);@lines = sort @lines;foreach $line (@lines) { print “$line\n”;}print “**No more**”;
Exercises● Write a program that reads from <STDIN> a set
of numeric values, one per line, and computes the mean and variance of these values. If N is the number of values, thenmean = (sum of all values) / N;variance = (sum square(each value – mean)) / N;
● Write a program that reads lines from <STDIN>, sorts these lines in reverse alphabetical order, prints the lines, and prints the total number of lines.
Hashes● A hash is a list of keyvalue pairs. The variable
name starts with %%age = (“Pablo”, 62, “Karen”, 23, “Paul”, 33);Here the key “Pablo” has value 62, the key “Karen” has value 23, and the key “Paul” has value 33.
● Accessing a hash by key$age{“Paul”} gives 33$age{“Karen”} gives 23
Hashes: Big Arrow Notation
● %lname = (“Pablo”=>”Manalastas”,“Rojo”=>”Sanchez”,“Joy”=>”Fernando”);
● %month = (1=>”January”, 2=>”February”,3=>”March”, 4=>”April”, 5=>”May”);
● $lname{“Rojo”} gives “Sanchez”$month{4} gives “April”
Using a Hash
● %lname = (“Pablo”=>”Manalastas”,“Rojo”=>”Sanchez”,“Joy”=>”Fernando”);print “Enter first name: “;chomp($fname = <STDIN>);print “Last name of $fname is “, $lname{$fname}, “\n”;
Keys & Values● %month = (1=>”January”, 2=>”February”,3=>”March”, 4=>”April”, 5=>”May”);
● @k = keys %month;# @k is the array of keys only
● @v = values %month;# @v is the array of values only
each() & exists()● %month = (1=>”January”, 2=>”February”,3=>”March”, 4=>”April”, 5=>”May”);
● To access each (key,value) pair: while(($key,$val) = each %month) { print “$key => $val\n”;}
● To check if a value exists for a keyIf( exists $month{13}) { print “That is $month{13}\n”;}
Hash Element Interpolation
● %month = (1=>”January”, 2=>”February”,3=>”March”, 4=>”April”, 5=>”May”);
● Can interpolate each elementprint “First month is $month{1}\n”;
● Not allowedprint “The months are: %month\n”;
Exercises
● Write a program that reads a series of words (with one word per line) until endofinput, then prints a summary of how many times each word was seen.
● Write a program that prompts for month number (112), day number (131), and year (19002008), and display the inputs in the form“MonthName day, year” (without the quotes).
Subroutines
● Userdefined functions that allow the programmer to reuse the same code many times in his program
● Subroutine name starts with &, in general● Defining a subroutinesub subName { subBody;}
Example Function
● Defining a function:
sub greet { print “Hello!\n”;}
● Using the function:
&greet;
Passing Arguments● If the subroutine invocation is followed by a list within
parenthesis, the list is assigned to special variable @_ within the function
● Example&greet(“Pablo”, “Jose”, “Maria”);
You can use the arguments as follows:sub greet { for each $name in (@_) { print “Hello $name!\n”: }}
Local Variables; Returning Values
● sub sum { local($total); $total = 0; for each $num in (@_) { $total += $num; } $total;}
Exercises
● Write a function that returns the product of its arguments
● Write a function that accepts two arguments n and d, returns a list of two numbers q and r, where q is the quotient of n and d, and r is their remainder
● Write a function that, given any number n as argument, prints the value of that number in words, as in a checkwriter.