290 likes | 448 Views
Programming in Unix. Control Structures Filehandles and File Tests Directory Operations Manipulating Files and Directories HTML. Control Structures. In an if control structure, the block of code is executed only when the conditional expression is true if ($name=fred){ }
E N D
Programming in Unix • Control Structures • Filehandles and File Tests • Directory Operations • Manipulating Files and Directories • HTML
Control Structures • In an if control structure, the block of code is executed only when the conditional expression is true if ($name=fred){ } • Unless is the opposite. Run the code unless the expression is true unless ($name=fred){ }
Control Structures • The else clause works with unless the same way it does with an if statement unless ($name=fred){ print “His name isn’t fred”; } else { print “His name is fred”; }
Expression Modifiers • Perl offers some variations on how to write some control structures if ($name=“fred”){ print “His name is fred. \n”; could be written as: print “His name is fred. \n” if ($name eq“fred”); • The conditional expression is still evaluated first, even though it’s written at the end • Perl is unable to handle multiple expression modifiers i.e.; if something while something
Naked Block • A “naked” block is a control structure without a keyword or condition, it just executes the body of the loop once while (condition) { #this works body; body; } { #this is a “naked” block body; body; }
Nested if • Use elsif when you have a nested if statement if ($name eq “fred”) { print “His name is fred\n”; } elsif ( $name eq “barney\n”) { print “His name is barney\n”; } else { print “I don’t know his name\n”; }
for Control Structure • The Perl for control structure works the same was as it does in C. It is usually used for making computed iterations for ($i=1; $i <= 10; $i++) { body; } Does the same as: initialization; while (test){ body; increment; }
for Control Structure • Perl will let you leave any of the three control parts empty, but you still need the semicolons for ( ; ; ){ print “This will leave you in an infinite loop”; }
for Control Structure • Another way to create an infinite loop is: while (1) { print “This is another infinite loop”; } • Make sure you have a way to exit the loop;
foreach Control Structure • Perl sees for and foreach the same. • If you have the two semicolons then it’s a computed for loop • If you don’t it’s a foreach loop for (1..10) { # works like a foreach print “I can count to $_ \n”; }
loop blocks • Perl is a structured programming language • Which means there is only one entrance to any block of code, which is the top of that block • There are five kinds of loop blocks: for, foreach, while, until, or the naked block
loop control operators • The last Operator • Perl’s equivalent for getting out of a loop early • If condition is true then last forces the loop to break out of the innermost enclosing loop block causing execution to continue with the statement immediately following the block (page 138)
loop control operators • The next Operator • next alters the ordinary sequence flow of execution. • Next causes execution to skip past the rest of the innermost enclosing looping block without terminating the block
loop control operators • The redo Statement • Causes a jump to the beginning of the current block • Works well when you need something initialized before the first test • Note: last, next and redo are used to jump out of a block not in
Logical Operators • && and || as Control Structures if (this) {that;} #or that if this; #or this && that; #logical and • If this is true, then the value of the entire expression is still not known, so that has to be evaluated • If this is false, there’s no point in looking at that
The Ternary Operator ?: • Works like an if-then-else test expression ? if_true_expr : if_false_expr; $location = &is_weekend($day) ? “home” : “work”; • You can nest it my $size = ($width < 10) ? “small” : ($width < 20) ? “medium” : ($width < 50) ? “large” : “extra-large”;
Directory Operations • The working directory is inherited by all processes that Perl starts • chdir changes the working directory chdir (“/etc”) || die “cannot cd to /etc”;
Globbing • Is a method of expanding filename patterns into the matching patterns • Globbing - * @a = glob “*”; #equals all files in your directory • Or put the pattern between angle brackets which is the old way (prior to version 5.6) @a = </etc/host*>;
Directory Handles • Directory Handles are not the same as file handles • Always opened read only • Value is true if directory can be opened, false if it cannot opendir (ETC,”/etc”) || die “Cannot opendir /etc:” ; closedir (ETC);
Directory Operations • Reading a directory handle • Each invocation of readdir is a scalar context returns the next filename • When no more to read returns undef opendir (ETC, “/etc”)|| die “no etc?”; while ($name = readdir (ETC) { print “$name\n”; } closedir (ETC);
Manipulating Files and Directories • To delete a file in Perl you use the unlink operator unlink “filename”; • To rename a file use rename rename “oldname” “newname”;
Manipulating Files and Directories • To create a directory use mkdir mkdir “directoryname”; or mkdir “directoryname”, 0700; #octal or $name=“CS345”; $permissions = “0755”; #needs leading zero or becomes 1363 octal mkdir $name, oct($permissions);
Manipulating Files and Directories • To remove a directory use rmdir rmdir “dir_name”; • To change file or directory permissions use chmod chmod 0755, “filename”;
Manipulating Files and Directories • When working with a file it’s good to test the file for certain characteristics such as does it exits, or is it an ordinary file $file = “data.txt”; if (-e $file) { print “File exists\n”; } else { die “File does not exist\n”; }
Using Perl to Generate a Web Page • To create a Perl script that will generate a Web page type #!followed by the location of the Perl interpreter • The source can be viewed but not the .pl code • To inform a Web browser that the script contains HTML code type print “Content-type: text/html\n\n”;
Using Perl to Generate a Web Page • To enter HTML code type print ; print “<html><head>”; • Repeat until you have entered all the Perl and HTML code • Save the script to your Web server • To access type in the URL of the page in the Web browser window.
Using Perl to Generate a Web Page #!/usr/local/bin/perl print “Content-type: text/html\n\n”; print “<html><head>”; print “<title>A Perl Web Page</title>”; print “</head><body>”; print “<h2> A Perl generated Web page </h2>”; print “Welcome”; print “</body></html>”;
Using Perl to Generate a Web Page • To create a Perl script that will generate a Web page, you must make sure you create or save the script in the correct directory • The directory used to store scripts is usually named cgi-bin • Contact the system administrator to verify that you are saving scripts in the correct directory • Make sure the directory, any subdirectories, and your files have permissions to read and execute