| program_name.pl v. 5.8.4 |
#!/usr/bin/perl statements |
$NotTheSame = "foo";
$notTHEsame = "bar";
|
# EOL comment |
variables: $scalar @list %hash |
Regex Operators
=~ (!~) | binding |
m/regex/ | matches regex |
m// | matches $_ |
/regex/ | matches regex |
s/srch/rep/ | search/replace |
tr/old/new/ | translate class |
| m// Operator Modifiers |
...regex/g | global search |
...regex/i | ignore case |
...regex/m | multiple lines |
...regex/o | compile once |
...regex/s | single line |
| s/// Operator Modifiers |
| same as m// modifiers |
| tr// Operator Modifiers |
...class/c | all chars not in class |
...class/d | delete non-replaced |
...class/s | remove dups |
Regex Defined Ranges
\d | digit [0-9] |
\w | alnum [a-zA-Z_0-9] |
\s | white [\t\n\r\f] |
\D | not \d [^0-9] |
\W | not \w [^a-zA-Z_0-9] |
\S | not \s [^\t\n\r\f] |
| |
|
Regex Meta Chars
/ | delimiter
(any char may be used) |
^ | start of string |
$ | end of string |
+ | 1 or more |
* | 0 or more |
? | 0 or 1 |
+? *? | non-greedy matching |
. | any char |
| | or |
() | grouping |
{n} | exactly n times |
{n,} | n or more times |
{n,m} | n up through m times |
[] | class |
\ | escape |
\b | word boundary |
\B | not word boundary |
| |
Regex Class Meta Chars
] | end class |
^ | not (if first char) |
- | range |
\ | escape next char |
| |
|
use: bignum strict Switch utf8(5.6) warnings; |
TMTOWTDI (Tim Toady) There's More Than One Way To Do It |
Arithmetic Operators
+ - * /
% modulus
** exponentiate
|
String Concatenate
string . string
String Repeat
string x number
|
Assignment
= += -= *= /=
%= **= .=
$arrarr[$i] = [@arr];
@arr = @{$arrarr[$i]};
|
Pre/Post (In/De)crement
++ --
List Enumerate
start .. stop
|
Text File I/O
open(HANDLE, "pathname"); open(HANDLE, "<pathname"); open(HANDLE, "<", "pathname");
above open for read. ">" opens for write; ">>" for append
while( <HANDLE> ) reads line into $_
@arr_name = <HANDLE> reads whole text file
if (-X pathname) file tests, where X=
| |
e exists;
r readable;
w writable;
z zero long;
|
|
d directory;
T text;
B binary;
s returns size
|
|
Comparison
numeric
==
!=
>
<
>=
<=
a <=> b
|
string
eq
ne
gt
lt
ge
le
a cmp b
|
1(a>b), 0(==), -1(<)
|
| Logical |
Bitwise |
| && |
and |
& |
| || |
or(xor) |
|(^) |
| ! |
not |
~ |
cond ? true : false;
evaluation short circuits
False: "" "0" 0 undef
True: non-false
<< SHL
>> SHR wo sign ext
|
Escapes in Double-Quotes
\a alarm
\b backspace
\e escape
\f formfeed
\n newline
\r return
\t tab
|
\v vert. ff
\\ backslash
\$ dollar sign
\@ at sign
\033 octal 033
\xff hex ff
|
|
Escapes in Single Quotes
\' single quote
\\ backslash
| Keywords |
my |
variable declaration |
q |
quote a string |
qw |
quote words |
|
|
|
| Statements |
$blockOfText = <<'ENDBLOCK';
block of text
ENDBLOCK
|
$var = expr; @arr = list; %hash = hash;
|
do { statement(s) to repeat }
while/until ( continuation condition );
|
expr; # chomp( $input );
|
for ( assignment; condition; increment )
{ statement(s) to repeat }
|
for[each] $var_name (@array_name)
{ statement(s) to repeat }
|
if (condition) { statement(s) }
[ elsif (condition) { statement(s) }] ...
[ else { statement(s) }]
|
|
last; break out of loop
|
next; to top of loop
|
package packagename;
|
return expr; within subroutine
|
sub subroutine_name() { code }
|
switch (value_to_match) {
case(val1|list|hash)
{code if val1 | in (list|hash)}...
[else {code if none of the above}]
|
unless ( break condition )
{ statement(s) to execute }
|
while/until ( continuation condition )
{ statement(s) to repeat }
|
|
Unstructured Statements: LABEL: goto reset |
Lists
| create: |
@arr_name = ( list of strings or numbers ); |
| |
@arr_name = qw / unquoted strings /; |
| |
@arr_name = other_array( start_index, stop_index ); |
| create 2D: |
@arr_name = ( [list] [,list]... ); |
| access: |
$arr_name[index] |
| access 2D: |
$arr_name[row index][col index] |
| access 2D: |
@sub_array = @{@arr_name[row index]} |
| extend: |
@arr_name[length]= value; push(@arr_name, value(s) ); |
| extend 2D: |
push(@arr_name, [list] ); |
| remove last: |
[$save_last_value=]pop(@arr_name); [...=]pop @arr_name; |
| truncate start: |
[$save_first_value=]shift(@array_name); |
| insert start: |
unshift(@array_name, new start element); |
| delete elements: |
splice(@array_name, first element to delete, # to delete); |
| insert elements: |
splice(@array_name, start element, 0, list); |
| replace elements: |
splice(@array_name, start element, # to replace, list); |
| last element: |
@array_name[$#array_name] # $#array_name is length - 1 |
| : |
|
| Note: splice returns element(s) deleted. |
|
Hashes
| create |
%hash_name = ( key=>value [,key=>value]... ); |
| create 2D |
%hash_name = ( key=>[list] [,key=>[list] ]... ); |
| add/replace record |
$hash_name{ key } = "value"; |
| add/rep record 2D |
$hash_name{ key } = [ list ]; |
| delete record |
delete( $hash_name{ key } ); |
| access value |
$hash_name{ key } |
| access value 2D |
$hash_name{ key }[ col index ] |
| access list 2D |
@{$hash_name{ key }} |
|
| list keys |
@all_keys = keys(%hash_name); |
| key exists |
exists($hash_name{key}); |
| list values |
@all_values = values(%hash_name); |
| step thru list |
while(($TheKey, $TheVal) = each(%hash_nam)) {...} |
| check for exists |
unless(exists($hash_name{key})) {...} |
| check for empty |
unless(%hash_name) {...} |
|
| Lists<->Scalars |
@list = ( $a, $b,...); | assign scalars to list |
my ( $a, $b,...) = @list; | assign list to scalars |
$scalar = @list; | $scalar = length of list |
$scalar = $#list; | $scalar = index of last element of list |
...foo( @list ); | same as ... foo( $list[0], $list[1], ...); |
...foo( \@list ); | passes reference to list |
$lref = $_[0]; | gets reference to list |
push( @$lref, $val ); | operates on referenced list |
@list = @$lref; | creates copy of referenced list |
| |
|
| String Functions |
chomp( string ); |
removes last char iff whitespace |
chop( string ); |
removes (and returns) last char |
index(string, substr_to_find[, from_index]); |
join( separ_chars, list ); |
converts list to string |
lc( string ); |
returns lowercase string |
lcfirst( string ); |
returns lc first letter string |
length( string ); |
returns length of string |
quotemeta( string ); |
escapes meta chars |
rindex(string, substr); |
rightmost substr |
split( /regex/, string ); |
splits to array |
sprintf( format, number ); |
more |
substr( string, start[, length] ); |
default: to EOS |
substr( string, -from_end, length[, replacement]); |
trim( str ) |
not built in (Google "perl string trim") |
uc( string ); |
return uppercase string |
ucfirst( string ); |
return uc first letter string |
|
|
| File Functions |
close( HANDLE ); |
|
glob( filespec ); |
returns names list |
mkdir(dirname, permissions); |
permissions: UNIX only |
open(HANDLE, [< > >>[,]] pathname); |
returns true on success |
opendir(HANDLE, path); |
|
read(HANDLE, buffer, len, pos); |
returns # read |
readdir(HANDLE); |
returns list of filenames |
rename(oldname, newname); |
returns success |
rmdir(dirname); |
|
seek(HANDLE, relpos, fromloc); |
|
select (HANDLE); |
reset STDOUT |
tell(HANDLE); |
returns current position in HANDLE |
truncate(HANDLE, newLength); |
|
|
|
|
| List Functions |
join( separator, list ); |
list to string |
map( expr, list ); |
apply expr to each element of list |
pop( @array ); |
|
push( @array, value(s) to push ); |
|
reverse( list ); |
|
scalar( @array ); |
$#array + 1 |
shift( @array ); |
pops and returns first element |
sort( list ); |
|
sort { sort cmp } ( list ); |
|
|
|
| Other Functions |
caller |
returns package name, filename and line number |
chdir( path ); |
|
chr( number ); |
chr(13) eq "\r" |
close( HANDLE ); |
|
die [msg] |
end w/line # or msg |
grep(regex, list); |
returns sublist |
$scalar=grep(regex, list); |
returns count |
hex( 'hexdigits' ); |
hex to number |
int( number ) |
round toward zero |
localtime( time ); |
sec. min. hr. dom. mon. yr. weekday |
log( number ); |
natural logarithm |
ord( char ); |
returns numeric value of char |
printf( format, number ); |
more |
pos( string ); |
next unmatched position during regex |
rand( max ); |
0 < double < max |
srand(); |
reset random seed |
require ( module ); |
include source of module (module returns true) |
|
|
|
Final word: I'm learning the LAMP stack Ps starting with Perl. Perl is a toolsmith's delight. I expect I'll be using it for the rest of my life. That said, Perl is a collection of kludges. Consider this: $ref = $_[1]; my @list = @$ref; That works, but the seemingly identical: my @list = @$_[1]; does not work. I was considering Perl for interfacing web pages and MySQL, but I'm not going to go there. Hopefully, PHP or Python will be more elegant.
|