View
217
Download
1
Tags:
Embed Size (px)
Citation preview
2.1
Lists and Arrays
2.1
2.2Summary of 1st lesson
• Single quoted and double quoted strings
• Backslash (\) – the escape character: \t \n
• Operators: numbers: + - * / ** strings: . x
• Variables: my $name;
• Reading input: $name = <STDIN>;
• Functions: length($name); substr($name,2,2);
2.3
Undefined variables
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.4Lists and arrays
A list is an ordered set of scalar values:
(1,2,3,"fred")
An array is a variable that holds a list:
my @a = (1,2,3,"fred");
print @a; 123fred
You can access an individual array element:
print $a[1]; 2
$a[0] = "*";
print @a; *23fred
2.4
012 3
scalar 1scalar 2scalar 3scalar 4
2.5Lists and arrays
You can easily get a sub-array:
my @a = (1,2,3,"fred","bob");
print @a; 123fredbob
print $a[1]; 2
my @sub_a = @a[2..3]
print @sub_a; 3fred
You can extend an array as much as you like:
my @b = (1,2,3)
$b[5] = 6;
@b is now (1,2,3,undef,undef,6)
2.5
012 3
scalar 1scalar 2scalar 3scalar 4
2.6Lists and arrays
Assigning to arrays:
my @a = (3..6); (3,4,5,6)
my @b = qw(a b cat d); ("a","b","cat","d")
my ($a,$b,@c) = (1..5); $a=1; $b=2; @c=(3,4,5)
Counting array elements:
print scalar(@a); 4
2.6
2.7Reading and printing arrays
You can read lines from the standard input in list context:
my @a = <STDIN>;
@a will store all the lines entered until the user hits ctrl-z.
You can interpolate arrays and array elements into strings:
print @b; abcatd
print "@b"; a b cat d
print "$b[2] is the third element of \@b";
cat is the third element of @b
2.7
2.8Manipulating arrays – push & pop
my @a = (1,2,3,4,5);
print @a; 12345
push(@a,6);
print @a; 123456
---------------------------
my @a = (1,2,3,4,5);
my $x = pop(@a);
print $x; 5
print @a; 1234
2.8
2.9shift & unshift
my @a = (1,2,3);
print @a; 123
unshift(@a,0);
print @a; 0123
-------------------------
my @a = (1,2,3);
my $x = shift(@a);
print $x; 1
print @a; 23
2.9
2.10split & join
my @a = split(",", "hello,how are you?,goodbye");
print "$a[1]\n";
how are you?
Now @a holds the list: ("hello","how are you?","goodbye")
my $str = join(":", @a);
print "$str\n";
hello:how are you?:goodbye
2.10
2.11Reversing lists
my @a = ("yossi","bracha","moshe");
print join(";", reverse(@a));
moshe;bracha;yossi
(You can also reverse strings…)
2.11
2.12Sorting lists
Default sorting is alphabetical:
my @a = sort("yossi","bracha","moshe"); # @a is ("bracha","moshe","yossi")
my @b = sort(1,3,9,81,243); # @b is (1,243,81,9)
Other forms of sorting require subroutine definition:
my @c = sort(compare_sub 1,3,9,81,243);
We’ll get to that latter…
2.12
2.13
The Debugger
2.13
2.14Debugging
A complex program will never work correctly the first time you run it! So:
• Write the program one stage at a time and check that it works
• Use a debugger to execute the program step by step
Next line that will be executed
2.15
Next line that will be executed
Start debugger Step one line
Run continuously Add breakpoint – to run until this point
2.16Choose “i/o” for interactive input
1
View printed output2
Enter input3
2.17You can “watch” your variables as they change their values using the “Watch List” window
Mark a variable name1
Click “Add Watch”
2
2.18
Enter expression
In order to “watch” arrays and more complex data use the “Evaluate Watch” button
2.19
Controls:Ifs and Loops
2.20Controls: if ?
Controls allow non-sequential execution of commands, and responding to different conditions.
else { print "Are you doing anything tomorrow night?\n";}
print "How old are you?\n";my $age = <STDIN>;if ($age < 18) { print "Sorry, I’m not allowed to chat with minors\n";}
2.21if, elsif, else
It’s convenient to test several conditions in one if structure:
if ($age < 18) { print "Sorry, I’m not allowed to chat with minors\n";} elsif ($age < 25) { print "Are you doing anything tomorrow night?\n";} elsif ($age < 35) { print "Are you married?\n";} else { print "Do you need help crossing the street?\n";}
2.22Comparison operators
ComparisonNumericString
Equal==eq
Not equal!=ne
Less than<lt
Greater than>gt
Less than or equal to
<=le
Greater than or equal to
>=ge
if ($age == 18)...
if ($name eq "Yossi")...
if ($name ne "Yossi")...
if ($name lt "n")...
2.23Boolean operators
if (($age==18) && ($name eq "Yossi"))...
if (!($name ne "Yossi"))...
if (!($name eq "Yossi:"
&& $age==18))...
And &&
Or ||
Not !
2.24Controls: Loops
Commands inside a loop are executed repeatedly (iteratively):
while ($name ne "Yossi") { chomp($name = <STDIN>); print "Hello $name!\n";}
foreach $name (@names) { print "Hello $name!\n";}
* There are also until, do-while and do-until loops
2.25Loops
$i=0;while ($i<scalar(@names)) { $name = $names[$i]; print "Hello $name!\n"; $i++;}
for ($i=0; $i<scalar(@names); $i++) { $name = $names[$i]; print "Hello $name!\n";}
A for loop is controlled by three statements:
• 1st is executed before the first iteration
• 2nd is the stop condition
• 3rd is executed before every re-iteration
These are equivalent
2.26Breaking out of loops
next – skip to the next iteration last – skip out of the loop
my @lines = <STDIN>;foreach $line (@lines) { if (substr($line,0,1) ne ">") { next; } print(substr($line,1)); if (substr($line,0,4) eq ">ehd") { last; }}
2.27Breaking out of loops
die – end the program and print an error message to the standard error <STDERR>
if ($score<0) { die "score must be positive"; } score must be positive at test.pl line 8.
Note: if you end the string with a "\n" then only your message will be printed
* warn does the same thing as die without ending the program