perl web

by dan 10/05/06 12:00:00 Article perl.


CGI.PM

nix-shell> which perl
    locate location of perl and add it to shebang #!/perl_path/perl in first line of code

CGI.PM
use CGI;
use CGI qw(param);
    # use cgi.param();
use CGI qw(:standard);
    # :standard= ""html2"",""form"",""cgi""
    # other values:
    # :cgi = arg handling, :netscape=netscape ext
    # :html2=html2.0, :html3=html3.0
    # :all = all
header();
    # returns ""Content-type:text/html\n\n"";
start_html(title);
    # returns ""<html><head>..<title>title.../head>""
end_html();
    # returns </body></html>
h1(text);
    # returns <h1>text</h1>
p(text);
    # returns <p>text</p>
hr();
    # <HR>
$val=param(""key"");
    # returns ""key"" param from URL #http//.../myscr?key=4

ex:

use CGI (:standard);
print CGI->header(),CGI->start_html(""intro""),h1(""hello"");
my $age=CGI->param(""age"");
print p(""age is $age"");
print CGI->end_html();

FORM GENERATION

start_form();
    # <FORM ACTION=...>
end_form();
    # </FORM>
textfield(""name"",""defaultStr"");
    # <INPUT type='text' name='name' value='defaultStr'>
popup_menu(""name"",['a','b','c']);
    # menu with choice a,b,c
    popup_menu(""name"",[1..3]);
    *[ .. ] = anonymous array
    @choice=('a','b','c');
    popup_menu(""var1"",\@choice));
    #\@= reference ptr to array
scroll_list(%arg);
    #param:
    -NAME=>""name"",
    -VALUES=>[qw(apple banana cherry)],
    # actual values that are passed in cgi
    -LABELS=>{apple=>""Delicious Apple"", banana=>""Yummy Banana""...}
    # each item can have label that is displayed in listbox.
    -SIZE=>3,       # # of item visible at once
    _MULTIPLE=>1  #1=can select more than 1. Param should be array.
    #  @arg=param(""flavors"");
    # TO pass by hash
    % fruit=(apple=>""Delicious Apple"",banana=>...);
    print scroll_list(_NAME=>""a"",_LABELS=\%fruit,...);

GET,POST in <FORM method=>

$ENV{'REQUEST_METHOD'}
    # returns GET or POST. If it is mixed, it is POST.
POST
    # all vars are passed to STDIN
    # $ENV{'CONTENT_LENGTH'}= length of posted str
GET
    # vars are passed to $ENV{'QUERY_STRING'}

ENV

$ENV{'HTTP_USER_AGENT'}
    Browser and OS type
$ENV{'HTTP_REFERER'}
    User's previous web page
To view all env var
    foreach(keys%ENV) {print ""$_ $ENV{$_}\n""}

Bibliography

  • Elizabeth Castro ""Perl & CGI: Visual Guide""
  • ""Learning Perl"" (aka Llama book)"


Digg! del.icio.us reddit furl