Perl - Pocket Guide
Shortest PERL Documentation
Petr Olivka , dept. of Computer Science, VSB-TU Ostrava, emailThis documentation is not for beginners, it is short pocket guide designed for little experienced users.
Content
- Variable
- Scalar
- Array
- Hash
- Reference
- Predefined variable
- Simple statement
- Compound statements
- Loop control
- For loop
- Foreach loop
- Regular expressions
- Files and Pipes
- Directories
Variable
$name scalar @name array %name associative array, hash table \$name, $$name reference, dereference Scalar - Number or String
Scalar - number or string, used acording to context.
$num = 32; $flo = 3.14; $ret = "hello"; print $num + $flo, "\n"; print "2^5 is", $num, "\n"; print "$ret, pi is $flo\n";Aritmetic operations and functions:
+, -, /, *, %, **, ++, -- Aritmetic operators ==, !=, <. <=, >, >= Equality operators ~, &, |, <<, >> Bitwise operators sin, cos, atan2, abs, sqrt, log, exp Math. functions int( x ), hex( str ), oct( str ), rand( n ), srand Other functions and, &&, or, ||, not, ! Logical operators String operations and functions:
eq, ne, lt, le, gt, ge Equality operators: . concatenate chomp delete EOL chop delete last char chr( ch ) return ordinal number of char index( str, substr [, offset ] ) position of substring or -1, start at offset join( separator, array ) return joined strings lc( str ) string to lower case lcfirst( str ) first char to lower case length( str ) number of characters ord( num ) get character form num rindex( str, substr [, offset] ) last position of substring, start before offset split( /pattern/, string [, limit ] ) splits string into array of string substr( str, +/-index [, +/-num [, new ] ] return string from index and replace with new, if defined uc( str ) string to upper case ucfirst( str ) first char to lower case Array
@ar1 = ( 1, 2, 3, 4, 5 ); @ar2 = ( "yes", "no" ); @ar3 = @ar1[ 1 .. 3 ]; ($yes, $no) = @ar2; print $ar2[ 0 ], "/", $ar2[ 1 ], "\n"; print @ar1[ 0, 2, 4 ], @ar3, "\n"; print "\@ar1: first index", $[, "\n"; print "\@ar1: last index ", $#ar1, "\n"; print "\@ar1: (", join ( ",", @ar1 ), ")\n";Functions:
pop( @ar ) delete and return last element push( @ar, list ) add list to end of array shift( @ar ) remove and return first element unshift( @ar, list ) prepend list to front of array splice( @ar, from [, num [, list ] ] remove and return num elements from and replace them with list, if defined Hash
Associative array is pair of key and value.
# key1 - val key2 - val key3 - val %speed = ( "slow", 50, "fast", 100, "fastest", 150 ); %speed2 = ( "slow" => 50, "fast" => 100, "fastest" => 150 ); $speed{ race } = 300; print $speed{ slow }; print $speed{ "fast" }; print $speed{ Fastest }; # key not defined ! print $speed{ 'race' }; print $ENV{ PATH }; foreach $k ( keys %ENV ) { print "$k\n"; } foreach $v ( values %ENV ) { print "$v\n"; }Functions:
delete( %speed{ key } ) delete key exists( %speed{ key } ) exists hash key ? keys( %speed ) return list of keys values( %speed } ) return list of values Reference
Reference can be defined for all types of variables.
$str = "hello"; @ara = ( 1, 2, 3 ); %hash = ( true, 1, false, 0 ); $rstr = \$str; $rara = \@ara; $rhash = \%hash; print $$rstr; # "hello" print @$rara; # print whole array - 123 print $$rara[ 1 ]; print ${$rara}[ 2 ]; # 3 print keys %$rhash; # truefalse print $$rhash{ "false" }; # 0Predefined variable
$_ default input $<digit> last pattern match $&, $MATCH last matched string $`, $PREMATCH string preceding matched string $', $POSTMATCH string following matched string $., $NR current line number $? status of last pipe, `` command or system() ($?>>8)=code, ($? & 255)=signal $! current errno $@ last eval() error $$, $PID this process number $<, $UID real uid of this process $>, $EUID efective uid $(, $GID real gid $), $EGID efective gid $0 script name $[ index of first array element $] perl version + pathlevel / 1000 $ARGV current file name when reading from <> @ARGV command line arguments $#ARGV last argument index, first is 0 @_ parameters passed to subroutine %ENV, $ENV{name} environment variables %SIG, $SIG{name} signal handlers Simple statement
The simple statement is an expression terminated with a semicolon.
Any statement may be followed by single modifier. The possible modifiers are:
- if EXPR
- unless EXPR
- while EXPR
- until EXPR
print "Hello\n" if $debug; die "No arguments\n" unless $#ARGV + 1; print while <>; $line = <> until $line =~ /^end/;Compound statements
Sequence of statements delimited by curly brackets is called a block.
To control flow may be used:
if (EXPR) BLOCK if (EXPR) BLOCK else BLOCK if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK LABEL while (EXPR) BLOCK LABEL while (EXPR) BLOCK continue BLOCK LABEL for (EXPR; EXPR; EXPR) BLOCK LABEL foreach VAR (LIST) BLOCK LABEL BLOCK continue BLOCKThe LABEL is optional.
Loop control
Two commands can be used in loop:
next LABEL skip rest of loop and start next iteration (like continue in C) last LABEL exit the loop and continue block is not executed (like break in C) For loop
For loop work like in C:
for ( Init_Expr; Condition_Expr; PostLoop_Expr ; ) { ... } for ( $i; $i < 10; $i++ ) { print $i; } # print 123456789Foreach loop
Foreach is synonym for for.
for $arg ( @ARGV ) { print "$arg\n"; } foreach $num ( 1, 3, 5, 7, 11, 17, 23 ) { print "$num is a prime\n"; } for $i ( 1 .. 10 ) { print "$i\n"; }Regular expressions
RegExp is used in pattern matching. The following metacharacters have their standard meaning:
\ quote the next metacharacter ^ begin of the line $ end of line . any character | alternation () grouping [] character class \d [0-9] \D [^0-9] \w [a-zA-Z0-9_] \W [^a-zA-Z0-9_] \s [ \r\n\t\f] \S [^ \r\n\t\f] Standard quantifiers:
* match 0 or more times + match 1 or more times ? match 1 or 0 times {n} match exactly n times {n,} match at least n times {n,m} match at least n and no more than n times Quantified pattern match as many times as possible. To match minimum number of times posible, follow the quantifier with ? - *?, +?, ....
Files and Pipes
<FILE> read from file getc( FILE ) read char from file open( FILE, name ) open file print FILE list print string printf FILE list print string close( FILE ) close file STDIN, STDOUT, STDERR standard file handles
'<name' open file for read '>name' create new file for write '>>name' open for append '+<name' open for read/write '+>name' '-' open stdin '>-' open stdout '| program' open program as pipe - for read "netstat |" Test file:
-r file is readable -w file is writable -x file is executable -e file exist -f is a file -d is a directory -l is a symbolic link -z file is empty -s file is not empty Directories
chdir( dir ) change directory chmod( rights, list ) change rights chown( uid, gid, list ) change owner closedir( DIR ) close opened directory link( existing, link ) make hard link mkdir( dir, rights ) make directory opendir( DIR, dir ) open directory readdir( DIR ) return next filename rename( old, new ) rename file rmdir( dir ) delete directory symlink( existing, link ) make symbolic link unlink( list ) delete files