PERLThese are my personal notes that I use as a quick help in my work.
|
|
A basic script. Save in a file with extension .pl and give executable permissions (755)
#!/usr/bin/perl |
/usr/bin/perl
should be the location of the perl on the server
(try which perl
).
There must be a blank line after the line with "content-type...
",
thus the double "/n/n
".
Notice the backslash before the quotes inside the tags. Likewise, escape the
following: \" \$ \@ \\
Debugger: perl -d script.pl
n for stepping over
s for stepping in (goes inside functions)
b $line_number or b $function_name: set breakpoint
b line boolean_expression: conditional breakpoint
d line: delete a breakpoint
c continue until a breakpoint
print $a_var: shows value
x $a_var: display variable with hierarchy
#!/usr/bin/perl -wT |
<Directory "${path}/www"><br />
#Added ExecCGI<br />
Options Indexes FollowSymLinks ExecCGI<br />
AllowOverride None<br />
Order allow,deny<br />
Allow from all<br />
</Directory><br />
<br />
<IfModule dir_module><br />
#added index.cgi<br />
DirectoryIndex index.html .... index.cgi<br />
</IfModule><br />
<br />
<IfModule mime_module><br />
TypesConfig conf/mime.types<br />
AddType ....<br />
#added these:<br />
AddHandler cgi-script .cgi .pl<br />
AddHandler server-parsed .html<br />
</IfModule>
#!/usr/bin/perl -wT
#!C:/perl/bin/perl.exe -wT
The second line is for Windows
The -w switch is for turning on warnings
The -T switch is to enable the taint checking
use strict;
Instructs the compiler to stop on unsafe constructs
vars --> must pre-declare variables
subs --> impacts sub routine calling
refs --> no symbolic references
use CGI;
Uses Lincoln Stein's CGI.pm module.
print <<END_HERE;
<html><head><title>Sample CGI Script</title></head>
<body bgcolor="#ffffcc"> ... </body></html>
END_HERE
Alternative to print "...."
my $time = localtime;
Put time in variable
"Standard:"+ , - , * , /
As in C: use ++, --, +=, -=
, ...
Power: **
String concatenation: . (a period)
Array concatenation: , (a comma)
Modulo: %
Sub-expression: ( ... )
Escape character is "\"
Use in: \\ \" \$ \@
\n New line
\r Carriage return
\t Tab
\xDD Character with hexadecimal DD
User input: <>
Example: print "Enter name:\n"; $name = <>; chomp($name); print "Hello, ", $name, "!\n";
Comment: #
Force declaration of variables: use strict;
Create local variable (or array or whatever): my $variable;
Create more than one: my ($a, @b);
Get warnings: use warnings;
Numerical comparison operators: == != < > <= >=
Boolean operators: && || !
(second operand not evaluated if not necessary: false && / true ||)
0, "", and undef
evaluate to false, all other values evaluate to true
An array: @array_name
An array element: $array_name[i]
, with i=0 to scalar(@array_name)-1 (to be confirmed)
Number of elements in the array: scalar(@myarray) or also $#myarray.
The last element: $myarray[-1]. Nth element from end: $myarray[-n]
Insert a variable's value in a string, with curly brackets to remove ambiguity: print "Show value: ${the_var_name}"
Conditional operators
Numeric test | String test | Description |
---|---|---|
== | eq | Equal to |
!= | ne | Not equal to |
> | gt | Greater than |
>= | ge | Greater than or equal |
< | lt | Less than |
<= | le | Less than or equal to |
<=> | cmp | Not equal to, with signed return |
if (cond) |
If else.if (0) { is like putting comments |
for $i (1..100) |
For loop |
for($a = 1, $b = 2 ; $a < 10 ; $a++, $b+=$a ) |
Another syntax of the for loop Separate the initial statements and iteration commands with a comma The interation commands are executed at the end of each iteration A "next" executes the interation statements. |
foreach $i (@an_array) |
Foreach loop |
while (cond) |
While loop |
A_LABEL: for $the_outer (1 .. 100) |
Exit to the outer loop by labelling the outer loop Personal opinion: labels are bad practice and lead to illegible code. |
sub sub_name |
Declare a sub routine. The arguments are in @_ |
exit(n) |
Exit the script with exit code n. n=0 ==> success; n>0 ==> failure |
sub sub_name |
Pass a reference to a variable so that it can be modified inside the function.\$a_variable gives the reference${$a_var} dereferences it |
length(string)
substr(the_string, offset, length)
int()
chomp
lc()
@components = split(/$regexp/, $string);
@a_filtered_text = grep(/$regexp/, @some_lines);
Arrays
push @an_array, @another
push @an_array, $an_element
@an_array = (@an_array, ...)
$a_var = pop(@an_array)
$a_var = shift(@an_array)
join("\n", @an_array)
@reversed_array = reverse(@an_array);
(@an_array) x $number
$scalar x $number
@ARGV
$ARGV[0]
is the first element
Arrays indexed by strings
$one_hash{"One entry"} = "a scalar";
$one_hash{$a_key}
keys(%one_hash)
exists($one_hash{$any_key}))
delete($one_hash{"a key"});
%hash1 = ("ct" => "Christopher", "my" => "Moussa", ...);
input/output: globs
open A_FILE_HANDLE, $mode, $the_relative_name;
open *afilehandle, $mode, $the_path;
print FILE $something, ...
close(THE_FILE)
$line = <INPUT_FILE>
join("", <THE_FILE>)
Regular Expressions
See section on regular expressions.
The expression $string =~ /$regexp/
returns a boolean
perform a substitution: $string =~ s/reg_expr/substitution/;
Perl excape sequences:
\w --> word character, equivalent to [A-Za-z_]
\W --> non-word character
\s --> whitespace character (space and tab)
\S --> non-whitespace character
\d --> digit, equivalent to [0-9]
\D --> non-digit.
\b --> word boundary. Zero width sequence
\B --> not a word boundary.
my $total = shift;
<>
while (<>) {print;}
($_ = <ARGV>)
while ($_ = <ARGV>) {print $_;}
map
sort
<=> and cmp
[ @an_array ]
{ %hash }
Encoding: for text
<form action="/cgi-bin/display.cgi" method="post" enctype="multipart/form-data">
...
</form>
Default encoding is enctype="application/x-www-form-urlencoded"
Sample script to read posted data:
#!... -wT
use strict;
my $the_buffer;
read (STDIN, $the_buffer, $ENV{'CONTENT_LENGTH'});
print "Content-type: text/plain\n\n";
print $the_buffer;
Using CGI.pm to handle request parsing
my $the_query = CGI->new();
my @the_name_value_pairs = $the_query->param;
print $the_query->header( "text/plain" );
foreach my $name ( @the_name_value_pairs ) {
my @the_values = $the_query->param( $name ); # generally one value, but just in case treat as collection
print $name . "=" . (join ", ", @the_values) . "\n";
}
$DISABLE_UPLOADS
= 1;
or write $CGI::$DISABLE_UPLOADS = 1;
at the beginning
of the script $POST_MAX = 51_200;
use CGI::Carp qw(fatalsToBrowser);
Local file: http://127.0.0.1/cgi-bin/printenv.pl