Tải bản đầy đủ (.ppt) (58 trang)

An introduce to perl

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (211.31 KB, 58 trang )

An Introduction to Perl
Sources and inspirations:
/>l
Randal L. Schwartz and Tom Christiansen,
“Learning Perl” 2nd ed., O’Reilly
Randal L. Schwartz and Tom Phoenix,
“Learning Perl” 3rd ed., O’Reilly
Dr. Nathalie Japkowicz, Dr. Alan Williams
Go O'Reilly!
CSI 3125, Perl, page 1
CSI 3125, Perl,
page 2
Perl overview (1)

Perl = Practical extraction and report language

Perl = Pathologically eclectic rubbish lister 

It is a powerful general-purpose language, which is
particularly useful for writing “quick and dirty”
programs.

Invented by Larry Wall, with no apologies for its lack
of elegance (!).

If you know C and a fair bit of Unix (or Linux), you
can learn Perl in days (well, some of it ).
CSI 3125, Perl,
page 3
Perl overview (2)


In the hierarchy of programming language, Perl is
located half-way between high-level languages
such as Pascal, C and C++, and shell scripts
(languages that add control structure to the Unix
command line instructions) such as sh, sed and
awk.

By the way:

awk = Aho, Weinberger, Kernighan

sed = Stream Editor.
CSI 3125, Perl,
page 4
Advantages of Perl (1)

Perl combines the best (according to its admirers )
features of:
Unix/Linux shell programming,
The commands sed, grep, awk and tr,
C,
Cobol.

Shell scripts are usually written in many small files
that refer to each other. Perl achieves the
functionality of such scripts in a single program file.
CSI 3125, Perl,
page 5
Advantages of Perl (2)


Perl offers extremely strong regular expression
capabilities, which allow fast, flexible and reliable
string handling operations, especially pattern
matching.
As a result, Perl works particularly well in text
processing applications.

As a matter of fact, it is Perl that allowed a lot of text
documents to be quickly moved to the HTML format
in the early 1990s, allowing the Web to expand so
rapidly.
CSI 3125, Perl,
page 6
Disadvantages of Perl

Perl is a jumble! It contains many, many
features from many languages and tools.

It contains different constructs for the same
functionality (for example, there are at least 5
ways to perform a one-line if statement).
It is not a very readable language.

You cannot distribute a Perl program as an
opaque binary. That is, you cannot really
commercialize products you develop in Perl.
CSI 3125, Perl,
page 7
Perl resources and versions


tells you everything that you
want to know about Perl.

What you will see here is Perl 5.

Perl 5.8.0 has been released in July 2002.

Perl 6 ( is the next
version, still under development, but moving
along nicely. The first book on Perl 6 is in stores
( />CSI 3125, Perl,
page 8
Scalar data: strings and numbers
Scalars need not to be defined or their types declared:
Perl understands from context.
% cat hellos.pl
#!/usr/bin/perl -w
print "Hello" . " " . "world\n";
print "hi there " . 2 . " worlds!" ."\n";
print (("5" + 6) . " eggs\n" . " in " . "
3 + 2 = " . ("3" + "2") . " baskets\n" );
invoke Perl
% hellos.pl
Hello world
hi there 2 worlds!
11 eggs
in 3 + 2 = 5 baskets
CSI 3125, Perl,
page 9
Scalar variables

Scalar variable names start with a dollar sign. They
do not have to be declared.
% cat scalar.pl
#!/usr/bin/perl -w
$i = 1;
$j = "2";
print "$i and $j \n";
$k = $i + $j;
print "$k\n";
print $i . $j . "\n";
print '$k\n' . "\n";
% scalar.pl
1 and 2
3
12
$k\n
CSI 3125, Perl,
page 10
Quotes and substitution
Suppose $x = 3
Single-quotes ' ' allow no substitution except for the
escape sequences \\ and \'.
print('$x\n'); gives $x\n and no new line.
Double-quotes " " allow substitution of variables like $x
and control codes like \n (newline).
print("$x\n"); gives 3 (and a new line).
Back-quotes ` ` also allow substitution, then try to
execute the result as a system command, returning as
the final value whatever the system command outputs.
$y = `date`; print($y); results in

Sun Aug 10 07:04:17 EDT 2003
CSI 3125, Perl,
page 11
Control statements: if, else, elsif
% names.pl
stan
'stan' follows 'fred'
my input
cut newline
Perl's output
% cat names.pl
#!/usr/bin/perl -w
$name = <STDIN>;
chomp($name);
if ($name gt 'fred') {
print "'$name' follows 'fred'\n";}
elsif ($name eq 'fred') {
print "both names are 'fred'\n";}
else {
print "'$name' precedes 'fred'\n";}
% names.pl
Stan
'Stan' precedes 'fred'
standard input
CSI 3125, Perl,
page 12
Control statements: loops (1)
% oddsum_while.pl
10
Use of uninitialized value at

oddnums.pl line 6, <STDIN> chunk 1.
The total is 25.
my input
% cat oddsum_while.pl
#!/usr/bin/perl -w
# Add up some odd numbers
$max = <STDIN>;
$n = 1;
while ($n < $max) {
$sum += $n;
$n += 2; } # On to the next odd number
print "The total is $sum.\n";
a warning
Perl's output
CSI 3125, Perl,
page 13
Control statements: loops (2)

End-line comments begin with #

It is okay, though not nice, to use a variable
without initialization (like $sum). Such a
variable is initialized to 0 if it is first used as a
number or to the empty string "" if it is first
used as a string. In fact, it is always undef,
variously converted.

Perl can, if asked, issue a warning (use the -w
flag).


Of course, while is only one of many looping
constructs in Perl. Read on
CSI 3125, Perl,
page 14
Control statements: loops (3)
% cat oddsum_until.pl
#!/usr/bin/perl -w
# Add up some odd numbers
$max = <STDIN>;
$n = 1;
$sum = 0;
until ($n >= $max) {
$sum += $n;
$n += 2; } # On to the next odd number
print "The total is $sum.\n";
% oddsum_until.pl
10
The total is 25.
CSI 3125, Perl,
page 15
Control statements: loops (4)
% cat oddsum_for.pl
#!/usr/bin/perl -w
# Add up some odd numbers
$max = <STDIN>;
$sum = 0;
for ($n = 1 ; $n < $max ; $n += 2) {
$sum += $n; }
print "The total is $sum.\n";
% oddsum_for.pl

10
The total is 25.
We also have do-while and do-until, and we have
foreach. Read on.
CSI 3125, Perl,
page 16
Control statements: loops (5)
% cat oddsum_foreach.pl
#!/usr/bin/perl -w
# Add up some odd numbers
$max = <STDIN>;
$sum = 0;
foreach $n ( (1 $max) ) {
if ( $n % 2 != 0 ) { $sum += $n; }
}
print "The total is $sum.\n";
% oddsum_foreach.pl
10
The total is 25.
CSI 3125, Perl,
page 17
Control constructs compared
C Perl (braces required)
the same
if () { } if () { }
if (! ) { } unless () { }
different
} else if () { } } elsif () { }
the same
while () { } while () { }

the same
for (aa;bb;cc) { } for (aa;bb;cc) { }
foreach $v (@array){ }
different
break last
different
continue next
similar 0 is FALSE 0, "0", and "" are FALSE
similar != 0 is TRUE anything not false is TRUE
CSI 3125, Perl,
page 18
Lists and arrays

A list is an ordered collection of scalars. An array is
a variable that contains a list.

Each element is an independent scalar value. A list
can hold numbers, strings, undef values—any
mixture of kinds of scalar values.

To use an array element, prefix the array name with
a $; place a subscript in square brackets.

To access the whole array, prefix its name with a @.

You can copy an array into another. You can use the
operators sort, reverse, push, pop, split.
CSI 3125, Perl,
page 19
Command-line arguments

Suppose that a Perl program stored in the file
cleanUp is invoked in Unix/Linux with the command:
cleanUp -o result.htm data.htm
The built-in list named @ARGV then contains three
elements:
('-o', 'result.htm', 'data.htm')
These three element can be accessed as:
$ARGV[0]
$ARGV[1]
$ARGV[2]
CSI 3125, Perl,
page 20
Array examples (1)
% cat arraysort.pl
#!/usr/bin/perl -w
$i = 0;
while ($k = <STDIN>) {
$a[$i++] = $k; }
print "===== sorted =====\n";
print sort(@a);
% arraysort.pl
Nathalie
Frank
hello
John
Zebra
notary
nil
control-D here
===== sorted =====

Frank
John
Nathalie
Zebra
hello
nil
notary
CSI 3125, Perl,
page 21
Array examples (2A)
% whole_rev.pl
a b c d
e f
g h i
== reversed ==
g h i
e f
a b c d
Reversing a text file (whole lines).
% cat whole_rev.pl
#!/usr/bin/perl -w
while ($k = <STDIN>) {
push(@a, $k); }
print "== reversed ==\n";
while ($oldval = pop(@a)) {
print $oldval; }
control-D here
CSI 3125, Perl,
page 22
Array examples (2B)

% each_rev.pl
a bc d efg
efg d bc a
hi j
j hi
klm nopq st
st nopq klm
Reversing each line in a text file
% cat each_rev.pl
#!/usr/bin/perl -w
while($k = <STDIN>) {
@a = split(/\s+/, $k);
$s = "";
for ($i = @a;
$i > 0;
$i ) {
$s = "$s$a[$i-1] "; }
chop($s);
print "$s\n"
}
output
control-D
split cuts the line on white space
(we will see regular expressions soon)
CSI 3125, Perl,
page 23
Array examples (3)
Reversing a text file (whole lines)
print reverse(<STDIN>);
Reversing each line in a text file

while($k = <STDIN>) {
$s = "";
foreach $i
(reverse(split(/\s+/, $k))) {
$s = "$s$i "; }
chop($s);
print "$s\n";
}
CSI 3125, Perl,
page 24
A digression:
Perl's favourite default variable
while(<STDIN>) {
$s = "";
foreach $i
(reverse(split(/\s+/, $_))) {
$s = "$s$i "; }
chop($s); print "$s\n";
}
by default,
Perl reads into $_
while(<STDIN>) {
$s = "";
foreach $i
(reverse(split(/\s+/ ))) {
$s = "$s$i "; }
chop($s); print "$s\n";
}
by default,
Perl splits $_ too!

CSI 3125, Perl,
page 25
Hashes

A hash is similar to an array, but instead of subscripts, we
can have anything as a key, and we use curly brackets
rather than square brackets.

The official name is associative array (known to be
implemented by hashing ).

Keys and values can be any scalars; keys are always
converted to strings.

To refer to a hash as a whole, prefix its name with a %.

If you assign a hash to an array, it becomes a simple list.

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×