On Perl

EMAIL: ADITYA (DOT) SINGH (AT) GMAIL

Name:
Location: Chicago/Delhi, United States

Friday, July 22, 2005

CGI - Keeping Perl and HTML separate

When ever you do CGI programming, you should keep your HTML and scripting (Perl) logic seperate.

HTML is the design aspect of your work, while Perl is the logic behind-the-scene that gets the data, manipulates it and finally displays it on the HTML page to the end-users.

Most of the CGI scripts found freely on the internet don't follow this approach. A cusory glance will show you it looks like a Zebra-code. The entire file is alternated between HTML and Perl. Their typical CGI file has some HTML tags in beginning like HEAD, TITLE etc. Then they have some perl logic, that get's data and modifies it. Some script even add a BOLD tag right there while generating the data. Then they concatenate this with other HTML strings.

In order to keep HTML and Perl separate, we'll have a minimum of two files. One is the Perl script - the one with business logic in it. And the other is the HTML content file. This is a perfect HTML file except it has place holders where Perl script will substitute it's data.

Eg. Zebra-code: CGI script with both HTML and Perl.

#!/usr/local/bin/perl
use CGI;
my $query = new CGI;

print <<"EndOfText";
Content-type: text/html

<HTML>
<HEAD>
<TITLE>My sample page</TITLE>
</HEAD>
<BODY>
<H1>Sample Page</H1>
EndOfText

my $name = $query->param('name');
print "Hello <B>$name</B>, how are you doing?<BR>\n";

my $address = get_address_of($name);
print "We found this as your address: <BR>$address<BR>\n" if ($address);
print "</BODY></HTML>";



Eg. CGI script with HTML and Perl seperated
HTML File is:

<HTML>
<HEAD>
<TITLE>My sample page</TITLE>
</HEAD>

<BODY>
<H1>Sample Page</H1>
Hello <B> %!name!% </B>, how are you doing?<BR>
We found this as your address: <BR> %!address!% <BR>
</BODY>
</HTML>


Perl script is:

#!/usr/local/bin/perl
use CGI;
my $query = new CGI;

my $name = $query->param('name');
my $address = get_address_of($name);

open(HTML, '<', './content.htm') or die "open failed\n";
my @html = </HTML>;
close(HTML);

chomp(@html);
my $html_str = join(/ /, @html);
$html_str =~ s/%!name!%/$name/g;
$html_str =~ s/%!address!%/$address/g;

print "Content-type: text/html\r\n\r\n $html_str"




Which one do you think is easier to read and hence, maintain?

Monday, July 11, 2005

Password generator

A simple routine to make passwords.


sub makePassword{
my $length = shift;
@chr = (0..9,'A'..'Z','a'..'z');
$passwd .= @chr[rand @chr] for 1..$length;
return $passwd;
}

print makePassword(10);
print makePassword(5);
print makePassword(1);