Advanced Topics Web Programming
Reference/Pointer A reference Syntax a pointer to something (e.g. array, hash) a variable that refer to other variables contain a memory address of data good for working with large data structures creating complex data structures Syntax to create a reference $ptr1= \$scalar; $ptr2= \@array; $ptr3= \%hash; $ptr4= [1, 2, 3]; $ptr5= { k1=>v1, k2=>v2} to get the value Variable (i.e. scalar, array, hash) $$ptr1; @$ptr2; %$ptr3; Element of array/hash $$ptr2[0]; $$ptr3{0}; $ptr2->[0]; $ptr3->{0}; Web Programming
Multi-dimensional Arrays Using anonymous arrays $array = [ [id1,pw1], [id2,pw2], [id3,pw3] ]; for ($i=0; $i<=2; $i++) { for ($j=0; $j<=1; $j++) { print “$array -> [i][j]\n”; } Using array references @a1= (id1,pw1); @a2= (id2,pw2); @a3= (id3,pw3); @array = (\@a1, \@a2, \@a3); # array of array pointers for ($i=0; $i<=2; $i++) { $ptr= $array[$i]; print “@$ptr\n”; Examples: #1, #2, #3, #4, #5 Web Programming
Fetching Web pages with LWP use LWP::Simple; $url= http://ella.slis.indiana.edu/~kiyang/hello.htm; $body= get($url); print $body; Example script use LWP::UserAgent; $ua = LWP::UserAgent->new(); $resp= $ua->get($url); $content=$resp->content(); print $content; Example script Form CGI Web Programming
WWW-Mechanize Module a subclass of LWP::UserAgent Basics Create a mech use WWW::Mechanize; my $mech = WWW::Mechanize->new( autocheck => 1 ); Fetch a page $mech->get( "http://ella.slis.indiana.edu/~kiyang/hello.htm" ); print $mech->content; Fetch a page into a file $mech->get( " http://ella.slis.indiana.edu/~kiyang/hello.htm", ":content_file" => “hello.htm" ); Get Links @links= $mech->links(); # @links: array of link object foreach $link(@links) { my($url,$text,$absurl)= ($link->url(), $link->text, $link->url_abs()); print “$url, $text, $absurl\n”; } Find Links $link= $mech->find_link(url_abs_regex=>qr|^http://ella.slis.indiana.edu|); $page= $mech->follow_link(url_abs_regex=>qr|^http://ella.slis.indiana.edu|); @pages= $mech->follow_all_links(url_abs_regex=>qr|^http://ella.slis.indiana.edu|); Mechanized Spider Example: #1, #2, #3 Web Programming
Perl DBI Module Basics Connect to a database Execute SQL Retrieve data use DBI; my $dbh = DBI->connect( DBI:Pg:dbname=$dbname; host=$host; $user, $pw ) || die “Can’t connect to DB: $DBI::errstr\n”; Execute SQL my $sql = “SELECT * FROM $table; my $sth = $dbh->prepare($sql); $sth->execute(); Retrieve data while (@row= $sth->fetchrow_array()) {; print join (“, “,@row),”\n”; } Disconnect from the database $dbh->disconnect(); Example Script: #1, #2 Perl DBI Manual Web Programming
Miscellaneous Features require “mylib.pl” store and use common subroutines in mylib.pl looks for mylib.pl in @INC directory add “return 1” at the end of “mylib.pl” example: mylib.pl, calling script #1 perlcc prog.pl –o prog.out generates a compiled binary named “prog.out” Web Programming