4.1 controls: ifs and loops. 4.2 controls: if ? controls allow non-sequential execution of commands,...

20
4.1 Controls: Ifs and Loops

Post on 19-Dec-2015

247 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.1

Controls:Ifs and Loops

Page 2: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.2Controls: if ?

Controls allow non-sequential execution of commands, and responding to different conditions

else {

print "Here is your beer!\n";

}

print "How old are you?\n";

my $age = <STDIN>; # Read number

if ($age < 18) {

print "How about some orange juice?\n“;}

Note the indentation:

a single tab in each line of new block

‘}’ that ends the block should be in the same indentation as where it

started

Page 3: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.3Comparison 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")...

if ($age = 18)...Found = in conditional, should be == at ...if ($name == "Yossi")...Argument "Yossi" isn't numeric in numeric eq (==) at ...

Page 4: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.4 if, else example

Consider the following code:my $luckyNum = 42;

print "Guess a number between 1 and 100.\n";

my $num = <STDIN>;

if ($num != $luckyNum) {

print "Sorry, wrong guess...\n";

} else {

print "WOW – you are right!!!\n";

}

Page 5: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.5 if, elsif, else

Sometimes it’s convenient to test several conditions in one if structure:my $luckyNum = 42;

print "Guess a number between 1 and 100.\n";

my $num = <STDIN>;

if ($num > 100) {

print "Number out of range\n";

} elsif ($num < 1) {

print "Number out of range\n";

} elsif ($num != $luckyNum) {

print "Sorry, wrong guess...\n";

} else {

print "WOW – you are right!!!\n";

}

Page 6: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.6Boolean operators

if (($age==18) and ($name eq "Yossi")){ print "Hi Yossi18";}if (($age==18) or ($name eq "Yossi")){ print "Hi You!";}if (!($name eq "Yossi")){ print "Hi man…"}

and && - True if both conditions are true or || - True if at least one condition is truenot ! - True if condition is False

and && - True if both conditions are true or || - True if at least one condition is truenot ! - True if condition is False

Page 7: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.7

my $luckyNum = 42;

print "Guess a number between 1 and 100.\n";

my $num = <STDIN>;

if ($num > 100) {

print "Number out of range\n";

} elsif ($num < 1) {

print "Number out of range\n";

} elsif ($num != $luckyNum) {

print "Sorry, wrong guess...\n";

} else {

print "WOW – you are right!!!\n";

}

Boolean operators

Page 8: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.8

my $luckyNum = 42;

print "Guess a number between 1 and 100.\n";

my $num = <STDIN>;

if ($num > 100 or $num < 1) {

print "Number out of range\n";

} elsif ($num != $luckyNum) {

print "Sorry, wrong guess...\n";

} else {

print "WOW – you are right!!!\n";

}

Boolean operators

Page 9: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.9 if (defined . . . )

There is an option to check whether a variable was defined:($inFile) = @ARGV;

open(IN, "<$inFile") or die "cannot open $inFile";

my @arr = <IN>;

if (defined $arr[9]) {

print "$arr[9]\n";

}

Page 10: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.10

You can ask questions about a file or a directory name (not filehandle):

if (-e $name) { print "The file $name exists!\n"; }

-e $name exists-r $name is readable-w $name is writable by you-z $name has zero size-s $name has non-zero size (returns size)-f $name is a file-d $name is a directory-l $name is a symbolic link-T $name is a text file-B $name is a binary file (opposite of -T).

File Test Operators

Page 11: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.11Class exercise 4a

Ask the user for his grades average and:

1. print "wow!" if it is above 90.

2. print "wow!" if it is above 90; "well done." if it is above 80 and "oh well" if it is lower.

3. print "wow!" if it is above 90; "well done." if it is above 80 and "oh well" if it is lower. Print an error message if the number is negative or higher than 100 (Use the or operator).

4*. Ask the user for a file name – and print a message stating whether or not the file exist.

Page 12: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.12Loops: while

Commands inside a loop are executed repeatedly (iteratively).The while loop is "repetitive if": executed while the condition holds.

my $luckyNum = 42;

print "Guess a number\n";

my $num = <STDIN>;

while ($num != $luckyNum) {

print "Wrong. Guess again.\n";

$num = <STDIN>;

}

print "Correct!!\n";

my $luckyNum = 42;

print "Guess a number\n";

my $num = <STDIN>;

if ($num != $luckyNum) {

print "wrong number..\n";

} else {

print "Correct!!\n";

}

Page 13: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.13Loops: while (defined …)

Let's observe the following code :open (IN, "<numbers.txt");my $line = <IN>;

while (defined $line) {chomp $line;if ($line > 10) {

print $line;}$line = <IN>;

}close (IN);

Page 14: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.14Loops: while

Let's observe the following code to compute factorial.(example 5! = 1*2*3*4*5 = 120).

my $num = <STDIN>;my $factorial = 1;my $currentNumber = 1;

while ($currentNumber <= $num) {$factorial = $factorial*currentNumber;$currentNumber++;

}print "Factorial of $num is $currentNumber\n";

Page 15: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.15Loops: foreach

The foreach loop passes through all the elements of an array

my @nameArr = ("Yossi","Daiana","Jojo");my $name;foreach $name (@nameArr) {

print "Hello $name!\n"}

Page 16: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.16Loops: foreach

The foreach loop passes through all the elements of an array

open (IN, "<numbers.txt");my @lines = <IN>;chomp @lines;my $num;foreach $num (@lines) {

if ($num > 10) {print $num;

}}close (IN);

open (IN, "<numbers.txt");my $line = <IN>;while (defined $line) {

chomp $line;if ($line > 10) {

print $line;}$line = <IN>;

}close (IN);

Page 17: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.17Breaking out of loops

next – skip to the next iteration last – skip out of the loop

open (IN, "<numbers.txt");

my @lines = <IN>;

chomp @lines;

foreach my $line (@lines) {if ($line eq "") { last; }if ($line <= 10) { next; }print $line;

}

close (IN);

Page 18: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.18Breaking 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

Page 19: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.19Fasta format

Fasta format sequence begins with a single-line description, that start with '>', followed by lines of sequence data that contains new-lines after a fixed number of characters:

>gi|16127995|ref|NP_414542.1| thr operon leader peptide…MKRISTTITTTITITTGNGAG>gi|16127996|ref|NP_414543.1| fused aspartokinase I and homoserine…MG1655]MRVLKFGGTSVANAERFLRVADILESNARQGQVATVLSAPAKITNHLVAMIEKTISGQDALPNAKFFAALARANINIVAIAQGSSERSISVVVNNDDATTGVRVTHQMLFNTDQVIEVFVIGVGGVGGALLEQNAGDELMKFSGILSGSLSYIFGKLDEGMSFSEATTLAREMGYTEPDPRDDLSGMDVARKLLILARETGRELELADIEIEPVLPAEFNAEGDVAAFMANLSQLDDLFAARVAKARDEGKVLRYVGNIDEDGVCRVKIAEVDGNDPLFKVKNGENALAFYSHYYQPLPLVLRGYGAGNDVTAAGVFADLLRTLSWKLGV>gi|16127997|ref|NP_414544.1| homoserine kinase [Escherichia coli…MG1655]MVKVYAPASSANMSVGFDVLGAAVTPVDGALLGDVVTVEAAETFSLNNLGRFADKLPSEPRENIVYQCWERFCQELGKQIPVAMTLEKNMPIGSGLGSSACSVVAALMAMNEHCGKPLNDTRLLALMGELEGRISGSIHYDNVAPCFLGGMQLMIEENDIISQQVPGFDEWLWVLAYPGIKVSTAEARAILPAQYRRQDCIAHGRHLAGFIHACYSRQPELAAKLMKDVIAEPYRERLLPGFRQARQAVAEIGAVASGISGSGPTLFALCDKPETAQRVADWLGKNYLQNQEGFVHICRLDTAGARVLEN

Page 20: 4.1 Controls: Ifs and Loops. 4.2 Controls: if ? Controls allow non-sequential execution of commands, and responding to different conditions else { print

4.20Class exercise 4b

1. Read a file containing several proteins sequences in FASTA format, and print only their header lines using a while loop (see example FASTA file on the course webpage).

2. Read a file containing several proteins sequences in FASTA format, and print only their header lines using a foreach loop (see example FASTA file on the course webpage).

3. (Ex 3.1b) Read a file containing numbers, one in each line and print the sum of these numbers. (use number.txt from the website as an example).

4*. Read the "fight club.txt" file and print the 1st word of the 1st line, the 2nd word of the 2nd line, and so on, until the last line. (If the i-th line does not have i words, print nothing).