perl: lecture 1 the language. what perl is merger of unix tools – very popular under unix –...
TRANSCRIPT
Perl: Lecture 1
The language
What Perl is
Merger of Unix tools– Very popular under UNIX– shell, sed, awk
Programming language– C syntax
Scripting language– Ability to change everything during runtime– Fast to employ, one-liners possible– Slower than C
What Perl is
Easy to learn– Learning curve similar to human language– More difficult things possible
Tell it to be more strict Object orientation
Esp. suited for the web & text processing– Regular expressions
How to get & use it
http://www.perl.com– ActiveState makes port for Microsoft Windows
Current Version is 5.8.0 Comprehensive documentation included
– C:\Perl\html\index.html– Perldoc
Running perl scripts– perl –w script.pl– #!/usr/bin/perl + chmod (Unix)
Variables
Scalars $ Arrays @ Hash % No need to declare variables Namespace for each variable type Case sensitive
Scalars
Number String Reference Automatic conversion of numbers and strings
$i = 1;$j = "2";print "$i\n";print "$j\n";$k = $i + $j;print "$k\n";print $i . $j . "\n";
Scalar Comparison Operators
Number String== eg
<> ne
< lt
> gt
<= le
=> ge
Truth
Any String is true except for „“ and „0“ Any number is true except for 0 Any reference is true Any undefined variable is false
The Perl if statement
if ($var==1) { commands1; }
elsif ($var==2) { commands2; }
else { commands3; }
unless ($var==3) {commands4; }
Arrays
Multivalued Variable Lookup by number List Assignments
Accessing
@home = ("couch", "chair", "table", "stove")($one, $two, $three, $four) = @home($one, $two) = ($two, $one)
$home[0] - $home[3]
Hashes
Multivalued Variable Lookup by name List Assignments
Accessing
%longday = ( "Sun" => "Sunday","Mon" => "Monday","Tue" => "Tuesday" );
@list = %longday
$longday{"Sun"}, $longday{"Mon"}
Quoting in Perl
Double Quotes ““ interprete variables and backslashes
Single Quotes ‘‘ don‘t
Own Quoting characters
q//, qq//
$one=“two”; $two=“four”;print ‘$one + $one is $two \n’;print “$one + $one is $two \n”;
Operators (1)
Arithmetic
String
Logical
% Modulus
** Exponentiation
. String concatenation
x Repeat operator
&&, and AND
||, or OR
!, not NOT
Operators (2)
File test operators
-e Exists
-r Readable
-w Writable
-d Is a directory
-f Is a regular file
-T Is a Text file
Iterative Structures
For
While
Foreach
while ($x<0.5) { $x = rand; }
for ($x=0; $x<10; $x++) { print “$x\n“; }
foreach $line (@lines) {
if ($line eq ““) last;
print reverse $line; }
Next and Last
next (continue in C) : start the next iteration of the loop.
last (break in C) : exit the loop.
Working with Files
open FILEHANDLE, EXPRESSION– Filehandle : means to access opened file– Expression : path of file to open, file mode
„<“ read (default) „>“ truncate and write „>>“ append
close FILEHANDLE
open LOG, ‘>>/var/log/mylog‘;
close LOG;
Input and Ouput
Print FILEHANDLE OUTPUT
„<FILEHANDLE>“ line reading operator
print LOG “Debug Message“;
$line = <LOG>;
@wholefile = <LOG>;
while ($line = <LOG>) {
print $line;
}
Default Variable
„$_“ default variable for functions
$_ = „222“;print log;
print while(<>);
Subroutines
Equivalent of C functions
Argument list, result list, no need to specify length
sub NAME {} # declaration
&NAME(); # invocation
sub arguments {my @params = @_;return @params;
}
@result = &arguments(@input);
Subroutines 2
„Named Parameters“
sub printtimes {my $string = shift;my $times = shift;while ($times-->0) {
print $string;}
}
$printtimes(„BA Stuggi\n“, 10);
Subroutines bonus
„@_“ for the main program : „@ARGV“
if (defined $ARGV[0]) {$loga = log $ARGV[0];print $loga;
}
print log (shift or exit);
Perl Regular Expressions (1)
(perlrequick)
Simple Pattern Matching
=~ Operator : boolean– TRUE for a match– FALSE for no match
"Hello World" =~ /World/; # matches
regex
delimiters
expression to match
Simple Pattern Matching Usage
1. if ("Hello World" =~ /World/) print "It matches\n";
2. if ("Hello World" !~ /World/) print "No match\n";
3. $teststring= "Hello World"; $greeting = "World";
if ($teststring =~ /$greeting/) print "It matches\n";
4. $_ = "Hello World";
if (/World/) print "It matches\n";
Simple Pattern Matching Bonus
Delimiters changable if „m“ is introduced
Match always at the earliest point possible Special characters („metacharacters“) require
masking
"Hello World" =~ m!World!; # matches
{}[]()^$.|*+?\
"2+2=4" =~ /2\+2/; # matches,'C:\WIN32' =~ /C:\\WIN/; # matches
Scalar Manipulation (1)
chop VAR / chomp VAR– Remove last character / Only if newline and return it
lc EXPR– Returns a lowercased EXPR
length EXPR– Returns number of characters in EXPR
index STR, SUBSTR [, POS]– Returns first position of SUBSTR in STR [after POS]
rindex STR, SUBSTR [,POS]– See above, uses last occurence
Scalar Manipulation (2)
sprintf FORMAT, LIST
%c a character with the given number %s a string %d a signed integer, in decimal %u an unsigned integer, in decimal %x an unsigned integer, in hexadecimal %f a floating-point number, in fixed decimal notation
substr EXPR,OFFSET [,LENGTH]– return the substring of EXPR starting from OFFSET
uc EXPR– Returns an uppercased EXPR