Date post: | 28-Dec-2015 |
Category: |
Documents |
Upload: | shonda-benson |
View: | 215 times |
Download: | 2 times |
Message from Greg
• You recently covered fopen, fread and fwrite. There are also unbuffered versions, open,read,write.
• The quiz: will be last ½ hour of class (not today- whenever he’s scheduled it). Questions will cover C stuff.
Introduction to Perl• Introduction
• History
• Invocation
• Basic Syntax
• Types
• Operators
• User Input
• Quoting
• Command Substitution
• Control
• Advanced/Esoteric stuff
• Slides: http://www.cim.mcgill.ca/~simra/cs206/
Introduction to Perl• Perl is a scripting language that makes
manipulation of text, files, and processes easy.
• Perl is often described as a cross between shell programming and the C programming language.
C
(numbers)
Shell programming
(text)
Smalltalk
(objects)
C++
(numbers, objects)
Perl
(text, numbers)
Java
(objects)
Introduction to Perl• A “glue” language. Ideal for connecting things together, such as
a gui to a number cruncher, or a database to a web server.
• Has replaced shell programming as the most popular programming language for text processing and Unix system administration.
• Runs under all operating systems (including Windows).
• Open source, many libraries available (e.g. database, internet)• Extremely popular for CGI and GUI programming. Is popular the
same as good?
• TMTOWTDI: Highly flexible and forgiving language. (but that can sometimes lead to trouble..)
History
• Developed by Larry Wall (www.wall.org)– Linguist– Programmer’s Virtues:
• Laziness: write labour-saving programs.• Impatience: write programs that pretend to anticipate your
needs.• Hubris: excessive pride- that which makes you go to the effort
to write and maintain good programs.
• Definitive Reference: “Programming Perl”, Wall, Christiansen, Schwartz. O’Reilly&Associates. (aka “The Camel Book”).
Invocation• Perl 5 is installed on most systems at CS.
• Invocation from the command line:[willy] [~] which perl
/usr/bin/perl
[willy] [~] perl ./hello.pl
Hello world!
• You can run the script directly if you make the script executable, and the first line uses ‘hash-bang’ notation:
[willy] [~] chmod +x ./hello.pl[willy] [~] cat ./hello.pl#!/usr/bin/perl -wprint "Hello world!\n";[willy] [~] ./hello.pl Hello world!
Basic Syntax (1)
• The -w option tells Perl to produce extra warning messages about potential dangers. Always use this option- there is never (ok, rarely) a good reason not to.
#!/usr/bin/perl -w
• Whitespace doesn't matter in Perl (like C++), except for #!/usr/bin/perl -w which must start from column 1 on line 1.
Basic Syntax (2)
• All perl statements end in a semicolon ; (like C)
• In Perl, comments begin with # (like shell scripts)– everything after the # to the end of the line is
ignored.
– # need not be at the beginning of the line.
– there are no C-like multiline comments: /* */
Perl Example 1 (1)
• Back to our “Hello World” program: [willy] [~] cat ./hello.pl
#!/usr/bin/perl -w# This is a simple Hello World! Program.print "Hello world!\n";
– The print command sends the string to the screen, and “\n“ adds a newline.
– You can optionally add parenths:print(Hello world!\n);
Basic Types• Scalars, Lists and Hashes:
– $cents=123;
– @home=(“kitchen”, ”living room”, “bedroom”);
– %days=( “Monday”=>”Mon”, “Tuesday”=>”Tues”);
• Advanced types: subroutines, references, typeglobs.
• All variable names are case sensitive.
Scalars
• Denoted by ‘$’. Examples: • $cents=2;• $pi=3.141;• $chicken=“road”;• $name=`whoami`;• $foo=$bar;• $msg=“My name is $name”;
• In most cases, perl determines the type (numeric vs string) on its own, and will convert automatically, depending on context. (eg, printing vs multiplying)
Scalar Example[willy] [~] cat ./scalar.pl #!/usr/bin/perl -w$number=23;$name="Bill Clinton";print "$name $number\n";
[willy] [~] perl ./scalar.pl Bill Clinton 23
Numerical Scalar Variables
• Perl supports the usual C numerical operations:$a = 25; # $a is now 25$a += 5; # $a is now 30$a *= 3; # $a is now 90$a++; # $a is now 91--$a; # $a is now 90$result = ($a + 2) * 3.4; # $result is 312.8
Lists
• Lists denoted by ‘@’:– @last=(“spring”, “is here”, time(), 4, $fun);– C-style array, but a single list can hold a variety of
items: scalars, other lists, hashes, subroutines etc.– Indexing begins at 0– DANGER: Accessing a scalar array element is a scalar
operation: (Probably the most common mistake):• $foo=@last[3]; WRONG!!! (unless last[3] is a list).• $foo=$last[3]; CORRECT.
– Always refer to scalar elements with ‘$’.
List Operations
• Assignment: – @items=(“I have”, 10, “dogs”);– $items[3]=“and an elephant”;– @mycopy=@items;– ($foo,$bar,$pet1,$pet2)=@mycopy;
• Other operations:– shift, unshift, push, pop, splice;
• Size: $#items is the index of the last element in the list:– $num_items=$#items+1;– print “I have $num_items items\n”;
• Printing magic: – print “@items\n”;# Will print all the elements of
# items,separated by spaces.
Hashes
• Denoted by ‘%’.• More advanced type of list. • Provides dictionary-style lookup.• Basis for perl’s object-oriented interface.• Example:
%myhash=(‘name’=>”Rob”, ‘age’=>29, ‘status’=“perennial student”);
$myname=$myhash{‘name’}; # access hash via {}print “$myname\n”;
Operators
• As mentioned, all C-style numerical operators supported,
plus exponentiation: – $a_to_the_b= $a ** $b;
• String operations:– $a=123; $b=3;– Concatenation: print $a . $b; #prints 1233– Repeat: print $a x $b # prints 123123123;
Operators, contd• Logical: all the C-style boolean operations: &&,!,||, etc.– Also, english-style operations:
• $a or $b, $a and $b, not $b.
• Primarily for readability:– open FILE, “<myfile” or die “Can’t open myfile”;
• Comparison: BE CAREFUL– Use different operators for strings and numericals. For example,
equality:• Numerical: $a == $b• Strings: $a eq $b
Operators
• Other comparison operators:– Equal: == vs eq.– Not equal: != vs ne.– Less than < vs lt– Greater than > vs gt– Less or equal <= vs le
User Input (1) • Use <STDIN> to get input from the user:
$ cat test2#!/usr/bin/perl -w print "Enter name: ";$name = <STDIN>;chomp ($name);print "How many girlfriends do you have? ";
$number = <STDIN>;chomp($number);print "$name has $number girlfriends!\n";$ test2Enter name: Bill ClintonHow many girlfriends do you have? more than
youBill Clinton has more than you girlfriends!
User Input (2) • <STDIN> grabs one line of input, including the
newline character. So, after:$name = <STDIN>;
if the user typed “Bill Clinton[ENTER]”, $name will contain: “Bill Clinton\n”.
• To delete the newline, the chomp() function takes a scalar variable, and removes the trailing newline if present. (If there is no newline at the end, it does nothing.)
• A shortcut to do both operations in one line is:chomp($name = <STDIN>);
Numerical Example $ cat test6#!/usr/bin/perl -wprint "Enter height of rectangle: ";$height = <STDIN>;print "Enter width of rectangle: ";$width = <STDIN>;$area = $height * $width;print "The area of the rectangle is $area\n";$ test6Enter height of rectangle: 10Enter width of rectangle: 5The area of the rectangle is 50$ test6Enter height of rectangle: 10.1Enter width of rectangle: 5.1The area of the rectangle is 51.51
Filehandles and ARGV
• Angle brackets are used to read from files, eg $line=<STDIN> reads a line from the STDIN filehandle.
• @ARGV is a special list, of the arguments passed to the script. Unlike C, $ARGV[0] is the first argument, not the executable name.
• <ARGV> is a special filehandle which treats all the arguments as files. So…
• $line=<ARGV> reads the next line from the concatenation of all the files on the command line.
ARGV Example
A simple version of ‘cat’:
#!/usr/bin/perl -w
while ($line=<ARGV>) {
print $line;
}
Notes:
while behaves like the C while.
<> is a synonym for <ARGV>.
If no argument is supplied, <ARGV> reads from STDIN.
More ARGV magic
TMTOWTDI: Another version of ‘cat’:#!/usr/bin/perl -w
while (<>) { print; }
This version takes advantage of some implicit functionality. Don’t sweat about the details.
Quoting• When printing, use escapes (backslash) to print special
characters:– print “She said \”Nortel cost \$$cost \@ $time\”.”– Output: She said “Nortel cost $0.01 @ 10:00”.
• Special chars: $,@,%,&,”
• Use single quotes to avoid interpolation:– print ‘My email is [email protected]. Please send me $’;
– (Now you need to escape single quotes.)
• Another quoting mechanism: qq() and q()– print qq(She said “Nortel cost \$$cost \@ $time”.);
– print q(My email is [email protected]. Please send me $);
– Useful for strings full of quotes.
Backquotes: Command Substitution• You can use command substitution in Perl like in shell scripts:
$ whoami clinton$ cat test7#!/usr/bin/perl -w$user = `whoami`;chomp($user);$num = `who | wc -l`;chomp($num);print "Hi $user! There are $num users logged on.\n";$ test7Hi clinton! There are 6 users logged on.
• Command substitution will usually include a newline, so use chomp().
Backquote Example 2 $ cat big1#!/usr/local/bin/perl5 -w$dir = `pwd`;chomp($dir);$big = `ls -l | sort +4 | tail -1 | cut -c55-70`;
chomp($big);$nline = `wc -l $big | cut -c6-8`; # NOTE: Backquotes
# interpolate.chomp($nline);$nword = `wc -w $big | cut -c6-8 `;chomp($nword);$nchar = `wc -c $big | cut -c6-8 `;chomp($nchar);print "The biggest file in $dir is $big.\n";print "$big has $nline lines, $nword words, $nchar characters.\n";$ big1The biggest file in /homes/horner/111/perl is big1.big1 has 14 lines, 66 words, 381 characters.
Control flow
If statements:if ($foo==10) {
print “foo is ten\n”;}print “foo is ten” if ($foo==10);if ($today eq “Tuesday”) {
print “Class at four.\n”;} elsif ($today eq “Friday”) {
print “See you at the bar.\n”;} else {
print “What’s on TV?\n”;}
Control flow, cont’d
You’ve already seen a while loop.
for loops are just like C:
for ($i=0; $i<10; $i++) {
print “i is $I\n”;
}
Advanced stuff
• Regular expressions (pattern matching):– print $foo if $foo=~/<a href/;– Very powerful for text processing.
• eval($foo) – evaluate a chunk of perl code. Very handy for parsers, embedding perl in web pages, etc.
• Objects, Modules.• CPAN: Online archive of modules.
Advanced Stuff
• Some handy modules:– FileHandle (more intuitive filehandle library)– LWP::Simple (simple web ops – page fetching,
etc).– XML::RSS (an RSS/RDF parser).– Date::Tolkien::Shire (do date manipulation in
the Shire calendar.)– Thousands more..