2-ListsAndArrays

Download Report

Transcript 2-ListsAndArrays

2.1
Scalar data - revision
numeric
string
3 -20 3.14152965
double quote:
6.35e-14 ( = 6.35 × 10-14)
print "hello\tworld";
hello
world
operators:
single quote (as is):
+
(addition)
-
(subtraction)
print 'hello\tworld';
hello\tworld
*
(multiplication)
/
(division)
** (exponentiation)
++ (auto-increment)
-- (auto-decrement)
operators:
.
x
(concatenate)
(replicate)
2.2
Variables - revision
Always use
use strict;
Variable declaration
my $priority;
String assignment
$priority = 'high';
Numerical assignment
$priority = 1;
Copy variable
my $max = $priority;
Change variable
$max++;
Interpolating in string
my $str = "max is $max";
print variable
print "$str\n";
print $str."\n";
Notes:
 Variable names in Perl are case-sensitive
 Give meaningful names to variables
2.3
Input & functions - revision
Read line from user
my $line = <STDIN>;
Remove "\n" (if exists)
chomp $line;
Length in characters
length($line);
Substring
substr(EXPR,OFFSET,LENGTH)
Note that OFFSET starts from 0.
Example:
my $string = "So Long, and Thanks for All the Fish";
my $sub = substr($string,1,4);
print $sub;
o Lo
2.4
Comments on exercises
• Always run your script with “perl -w” and take care of all
warnings  submitted scripts should not produce any warnings
• When you email us problems you run into, send the script, and copy
the running of it (with “perl -w”) and the output from the
command prompt window
• When submitting exercises by email write your name and the
exercise number in the subject line (for example “Shmulik
Israeli perl ex. 2”)
• Write a separate file for each question, and name the scripts:
“ex2.1.pl”, “ex2.2.pl”, “ex2.3.pl”…
2.5
Comments on exercises
• Use meaningful names for variables.
• We always add "use strict;" in the first line of scripts (once is
enogh).
• Always declare variables using "my $newVarName;" .
• Use chomp function to omit newline ("\n") from input.
2.7
Adding comments
Comments: The # symbol, and anything from it to the end of the line
is ignored.
# get start and stop values from the user
my $start = <STDIN>
my $stop = <STDIN>
# calculate string length
my $length = $start - $stop + 1;
2.8
Adding comments
Comments: If you want to insert a comment of multiple lines, you can use
=begin and =cut.
=begin
This program prints stuff.
Here you can write any text you want
and you don’t need any #
=cut
print "stuff\n";
2.9
Uninitialized variables
• If uninitialized variables are used (before assignment) a warning
is issued:
my $a;
print($a+3);
Use of uninitialized value in addition (+)
3
print("a is :$a:");
Use of uninitialized value in concatenation (.) or string
a is ::
2.10
Lesson 2:
Lists and Arrays
2.11
Lists and arrays
A list is an ordered set of scalar values:
(3,2,1,"fred")
An array is a variable that holds a list:
my @arr = (3,2,1,"fred");
print @arr;
321fred
You can access an individual array element:
print $arr[1];
2
$arr[0] = "*";
print @arr;
*21fred
3
2
1
"fred"
@arr
3
*
2
1
"fred"
0
1
2
3
2.12
Lists and arrays
You can easily get a sub-array:
my @arr = (3,2,1,"fred","bob");
print @arr;
321fredbob
2
3
print $arr[1];
2
0
1
my @sub_arr = @arr[2..3];
print @sub_arr;
1fred
You can extend an array as much as you like:
my @arr2 = ("A","B","C")
$arr2[5] = "F";
@arr2
@arr2
"A"
"B"
0
1
@arr
1
"fred" "bob"
2
3
@sub_arr
1
"fred"
0
1
"C" undef undef "F"
2
3
4
5
4
2.13
Lists and arrays
Assigning to arrays:
my @arr = (3..6);
# same as @arr=(3,4,5,6);
Multiple assignment:
my ($a,$b) = ('cow','dog');
$a='cow'; $b='dog';
my ($a,$b,@c) = (1..5);
$a=1; $b=2; @c=(3,4,5)
scalar - counting array elements:
print scalar(@arr);
4
Last element index:
print $#arr;
3
2.14
Arrays in scalar context
Consider the following:
my @arr = ('a','b','c','d');
my $num = $#arr;
$num = 3
This one will be very
my $num = @arr;
useful in the future
$num = 4
my ($num1, $second) = @arr;
$num1 = 'a'
$second = 'b'
2.15
Interpolating arrays
You can interpolate arrays and array elements into strings:
my @arr = ("a","b","cat",d");
print @arr;
abcatd
print "@arr";
a b cat d
print "$arr[2] is the third element of \@arr";
cat is the third element of @arr
2.16
Reading arrays
You can read lines from the standard input in list context:
my @arr = <STDIN>;
print "@arr";
@arr will store all the lines entered until the user hits ctrl-z.
ctrl-z to indicate
end of file
@arr2
"cogito\n" "ergo\n" "sum\n"
2.17
Reading arrays
chomp will work on entrie arrays:
my @arr = <STDIN>;
chomp @arr;
print "@arr";
@arr2
"cogito\n"
"cogito" "ergo\n"
"ergo"
"sum\n"
"sum"
2.18
Manipulating arrays – push & pop
my @arr = ('a','b','c','d','e');
print @arr;
abcde
push(@arr,'f');
print @arr;
abcdef
----------------------my @arr = ('a','b','c','d','e');
my $num = pop(@arr);
print $num;
e
print @arr;
abcd
e
d
c
b
a
@arr
5
4
3
2
1
0
$num
2.19
shift & unshift
my @arr = ('a','b','c');
my $num = shift(@arr);
print $num;
a
print @arr;
bc
--------------------my @arr = ('a','b','c');
print @arr;
abc
unshift(@arr,'?');
print @arr;
?abc
0
1
2
3
4
2.20
split & join
my @arr;
my @arr2;
@arr = split(/ /, "You talkin to me? You talkin to me?");
@arr = ("You","talkin","to","me?","You","talkin","to","me?")
@arr2 = split(//, "You talkin to me? You talkin to me?");
@arr2 = ("Y","o","u"," ","t","a","l","k","i","n"," ",...)
my $str = join("-", @arr);
print "$str\n";
"You-talkin-to-me?-You-talkin-to-me?"
2.21
Reversing lists
my @arr = ("yossi","bracha","moshe");
my @rev_arr = reverse(@arr);
print join(";", @rev_arr);
moshe;bracha;yossi
2.22
Sorting lists
Default sorting is alphabetical:
my @arr = sort("yossi","bracha","moshe");
# @arr is ("bracha","moshe","yossi")
my @arr2 = sort(1,3,9,81,243);
# @arr2 is (1,243,3,81,9)
Other forms of sorting require subroutine definition:
my @arr3 = sort(compare_sub 1,3,9,81,243);
We might get to that latter…
Note: sort and reverse do not change the array.
They return a new array after the operation of the function
(that should be saved in another array if needed for further use).
2.23
Class exercise 2.1
1.
Read a number from the first line of input, and then read
the rest of the lines into an array (stop by using ctrl-z).
Print the line selected by the number provided in the first line.
2.
Read a list of numbers separated by spaces, and print those numbers in
reverse order, separated by slashes (/).
3.
Read a list of words separated by spaces, sort and print them.
4.
Like in 3, but return only the last word (after the sorting).
5.
Like in 3, but reverse the order of the letters of the last word
2.24
@ARGV
It is possible to pass arguments to Perl from the command line. These Command-line
arguments are stored in an array created automatically named @ARGV:
@ARGV
"Hi" "man"
5
use strict;
my $joinedArr = join("\n",@ARGV);
print $joinedArr;
2.25
@ARGV
It is possible to pass arguments to Perl from the command line. These Command-line
arguments are stored in an array created automatically named @ARGV:
@ARGV
"Hi man"
5
use strict;
my $joinedArr = join("\n",@ARGV);
print $joinedArr;
2.26
Class exercise 2.2
1.
Read a list of numbers from the command-line (using @ARGV),
and print those numbers in reverse order, separated by slashes (/).
2.
Read a list of words from the command-line, sort and print them.
3.
Like in 2, but return only the last word (after the sorting).
4.
Like in 2, but reverse the order of the letters of the last word