Site Moved

This site has been moved to a new location - Bin-Blog. All new post will appear at the new location.


Inline Perl code in HTML

I would always recommend PHP over Perl when it comes to web development. PHP was created with just one purpose - Web Development. Perl, on the other hand, can be used in many different ways - one of which is web development. I began using Perl much before I began using PHP. I have been using PHP for just over a year but I have been using perl for at least 3 years now. I have even written a tutorial on CGI using the Perl language.

One of the main advantage of using PHP is that you can embed PHP code inside HTML files - just give it the extension '.php' and the server will parse it and serve the resulting page. In Perl, you will have to embed HTML code in perl's print statements - this is a much tougher approach.


There are some programs like BML which will let you embed Perl script into HTML files - LiveJournal uses this approach. But the trouble with this approach is that you will have to have access to the server's 'httpd.conf' file. You will have to configure the server to parse all the files with the '.bml' extension with a script provided by you.

I tried to solve this problem a few months ago - I made a small script called H2P that will parse all file with the extension '.perl'. This don't need any server side configuration so the installation process was much simpler. The only necessary thing was '.htaccess' and the 'mod_rewrite' Apache module. Unfortunately, this project failed and failed miserably. And since I had the PHP option to fall back on, I did not go to great lengths to try to fix it.

Even thought that project was a failure, I created this little gem. This function will let you execute a small bit of Perl code embedded inside a HTML file like this...

<p>This is just html code. <?perl print "This is Perl code."; ?>
Html code once again.</p>

The final output will be like this.

<p>This is just html code. This is Perl code.
Html code once again.</p>


sub showFile {
 my $file = shift; #The first argument is the file name.
 open(IN,$file) or die "Can't read display page '$file' : $!";
 my @lines = <IN>;
 close IN;

 my $count = 0;
 for(my $i=0; $i<scalar(@lines); $i++) {
  my $line = $lines[$i];
  if($line =~ /<\?perl/i) {
   #If there is a perl code embedded in this, get the code to the finishing point
   my $code = "";
   my $j;
   for($j=$i; $j<scalar(@lines); $j++) {
    my $this_line = $lines[$j];
    $code .= $this_line;
    last if($this_line =~ /\?>/);
   if($code =~ /(.*)<\?perl(.+?)\?>(.*)/is) { #Take out the code.
    my $text_before_code = $1;
    $code = $2;
    my $text_after_code = $3;
    print $text_before_code;
    #Execute the code.
    eval $code;
    die $@ if $@; #Die if there was an error.
    print $text_after_code;
   $i = $j;
  } else {
   print $line;

#Print the contents of a file after parsing it.


No Automatic Parsing
Does not parse the files with a specific extension - you will have to call the file via the 'showFile(file_name)' function.
Local scope
The code within the <?perl ... ?> is 'eval'ed. So all the variables that was created in that block exists only within that block. If you have used the 'use strict;' option(and you must), this will limit you very much. If you mush use a variable from another block, you will have to make it a global variable using 'use vars qw($variable_name);'. Still, better than nothing.

Filed Under...


XML Parser function for JavaScript - xml2array()

I have created a small function called 'xml2array()' that will take an XML document as the argument, parse it and return an associative array as the result. This array will contain the data of the XML file - which can be easily accessed - without resorting to writing codes with xml.childNode or node.nextSibiling or any other stuff like that. Take a look at the Demo page.

XML Parsing in JavaScript

One have to admit that parsing XML code in JavaScript is relatively easy. We already have a DOM parser in place and we can use the functions provided by it to parse the XML documents. The functions like getElementsByTagName() can be used to make parsing XML documents much easier.


Compare that with, say, ActionScript - they have no getElementsByTagName. This makes it much more difficult to parse XML documents. I was hoping that this function will make XML parsing easier for ActionScripters also. But before using this code in ActionScript, please note that I don't know ActionScript - I only know JavaScript - and since the two are very similar, I was hoping that my script will work in Flash too - since they need it much more than we do. But it don't - my script creates some errors in Flash - if any of you could get it working in flash, please let me know.


Anyway, the script can still be used in JavaScript for parsing XML returns in Ajax scripts. So if you use XML as the response data format for your ajax program, be sure to get a copy of the code for xml2array.


Updated version of jx Ajax Library

The smallest Ajax library - jx has been very useful for me - so much that it found its way to the common.js file of the Bin-Co site. So I thought that I will release a slightly updated version.

// jx Library - (Version 1.01.A)
var jx = {
 http : false,
 getHTTPObject : function() {
  var xmlhttp = false;
  if(typeof ActiveXObject != 'undefined') {
   try {xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");}
   catch (e) {
    try {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
    catch (E) {xmlhttp = false;}
  } else if (XMLHttpRequest) {
   xmlhttp = new XMLHttpRequest();
  return xmlhttp;
 getData : function(url,callback,type) {
  if(!this.http) {
   if(!this.http) return;
  if(!type) var type = "text";"GET", url, true);
  this.http.onreadystatechange = function () {
   if (jx.http.readyState == 4) {
    var result = "";
    if(jx.http.responseText) result = jx.http.responseText;
    type = type.toLowerCase();
    if(type == "json" || type == "j") result = eval(result);
    if(callback) callback(result);

 init : function() {
  this.http = this.getHTTPObject();

//////////////// Init ///////////
//Call it like this.
function init() {
 jx.getData("data.php?id=3&whatever=something",function (data) {


Very little changes to speak of, but here goes.

  • Removed the comments to make the code smaller - if you need to see how the code works, see the original post on the jx Ajax Library.
  • Don't have to call the jx.init() function - the script does it automatically.
  • Made the code smaller.
  • Some more small changes.

Ajax Response Data Formats

Some time ago, Peter Paul Kosh wrote an article about the different types of Ajax data formats - The AJAX response: XML, HTML, or JSON?. I know that it is a bit late but this is my views on the topic.


I prefer JSON as it is the easiest to parse - just put an 'eval' and we are done. My biggest issue with this is the text created by the server-side script is next to unreadable by human beings. This makes it very hard to debug our Ajax scripts.


My second favorite place goes to Plain text format as it is the easiest to generate. I use plain text only when there is just a single unit of data - when I want the email address of an user from the database or if I want to know wether the given username exists in the database - the response data will be just a '1' or a '0' in this case.


Next in line comes the HTML format - the easist to display. $("display").innerHTML = http.responseText is all it takes to get the job done. This method is commenly known as AHAH.


Last but not the least comes the XML format - the most portable solution. Unfortunatly, XML format is the most difficult to parse.

My jx Ajax Library provides support for both Text and JSON data formats. One can use the Text support of this library for getting HTML data. It does not support XML format as of yet and I have no intension to add that support to my library as I want to keep it as small as possible.

So I created another small Ajax with XML library called xjx that would do the trick...

///////////////////////////////////// xjx - XML Ajax Library //////////////////////////////////////
var xjx = {
"handler":function () {//Firefox only function - happens when a XML file is loaded
 if(!this) {
  return false;
 if(xjx.callback) xjx.callback(this);

//Load the xml file - using different method for different browsers 
"load":function (xml_file,callback) {
 this.file = xml_file;
 this.callback = callback;
 var xmlDocument;
 if(document.implementation.createDocument) {//Firefox
  xmlDocument = document.implementation.createDocument('', '', null);
  xmlDocument.addEventListener('load', this.handler, false); //This function will happen when the file is loaded
 else { //IE
  xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
  xmlDocument.async = false;
  var loadResult = xmlDocument.load(xml_file);
  if (loadResult) {
   if(callback) callback(xmlDocument);
  else {
   return false;
 this.xml = xmlDocument;
 return true;
"error":function (from) {//Any error messages?
 alert("Error reading the XML file '" + this.xml_file + "'");
 return false;

You can call it from your script like this...

xjx.load("file.xml",function(xmlDoc) {

Moving the Blog from Blogspot

Now that I have broken my dependence on GeoCities, I think I am going to do the same with Blogger. I have been using Blogger to host my blog for almost a year - and I am very happy with their service. But I think it is time to go professional - build a Blog on my own domain - using a software that I could customize to fit my own needs. It will take some time but I think will do it.

Jakob Nielsen, the usability guru have given a list of mistakes you can make in blogging(something I blogged about before) and the last one is about having a Domain Name Owned by a Weblog Service.

Having a weblog address ending in,, etc. will soon be the equivalent of having an email address or a Geocities website: the mark of a naive beginner who shouldn't be taken too seriously.

I am not very sure that having a '' address will automatically demote one's site in others eyes - I have seen many great blogs on free services, but I am a web developer and I will be disregarded if I am using a free service to create my site. These blogging platforms provide the lowest entry point to web publishing - I will not come out good if I continue using this service - now that I have an option to use my own site to do the blogging.

But the main reason I am switching is because of JavaScript. Blogger will not allow me to insert JavaScript code into the post - this prevents me from making a demo of even the simplest scripts on the page. I have to depend on an external site if I wish to create a demo page.

Also if I use a professional option, I get to use WordPress - I really wanted to learn this blogging platform. Another alternative is to stick with Blogger - but use their FTP option to upload the posts directly to my site. But this option will not solve the JavaScript problem described earlier.

What do you think of my decision - good or stupid? Did any of you experience a similar situation? If yes, how did you solve it?


CSS Shorthand

CSS Shorthand is a method to compress multiple declarations into one declaration. Two or more related declarations can be compressed to form one easily readable declaration. For example...

can be written as
border:1px solid blue;

In my CSS coding style manual, I feel that I have not given enough importace to this topic. I will try to remedy that in this post. Before beginning familiarize yourself with some css terminology that I will be using in this page.

A style parameter that can be influenced through CSS. Eg 'font-size'.
A property e.g. 'font-size' and a corresponding value e.g. '12pt'.
A declaration (e.g. 'font-family: helvetica') and its selector (e.g. 'h1').
A string that identifies what elements the corresponding rule applies to. A selector can either be a simple selector (e.g. 'h1') or a contextual selector (e.g. 'h1 b') which consists of several simple selectors.
See full list of standard CSS Terminology

Why use Shorthand?


Smaller Code
The shorthand code is smaller - saving the download time of the vistor and the bandwidth of the server.
More Manageable
Smaller code means more manageable code. As this method brings all the related rules together, it easy to edit these rules.
Improved readability
In most cases(exceptions below) proper useage of shorthand improves readability. It is easier to read CSS code when all the related rules are bunched together.


Decreases Readability - in some cases
I know that I have given 'Improved Readability' as one of the advantages. But one requirement for reading shorthand CSS code is that you must know the rules for writing the shorthand for that selector. Anyone can understand what this means...
But to understand margin:1px 2px 3px 4px; you have to know how the shorthand rule for the margin property. Is this an excuse to avoid shorthand? No - it is an excuse to learn shorthand rules!


The most commonly used shorthand properties are given below.


border: <border-width> || <border-style> || <color> ;

.box {

.box {
 border:1px solid blue;


font: [ <font-style> || <font-variant> || <font-weight> ]? <font-size> [ / <line-height> ]? <font-family>;

p {
p {
 font: italic small-caps bold 12px/14px sans-serif;


background:<background-color> || <background-image> || <background-repeat> || <background-attachment> || <background-position> ;

#board {
 background-position:top left;
#board {
 background:#666 url(chess.png) repeat fixed top left;


margin : <width> - 1 to 4 times

body {

body {
 margin: 1px 2px 3px 4px;/* top=1px, right=2px, bottom=3px, left=4px */
The value order must be in a clockwise direction starting at the top - top, right, bottom and left.


padding : <width> - 1 to 4 times

body {

body {
 padding: 1px 2px 3px 4px; /* top=1px, right=2px, bottom=3px, left=4px */


Filed Under...

Read More... Completed Logo

The work on my new site is over - is open for business. All the pages from my old site have been converted to dynamic PHP pages. Now SEO is the only thing left to do.

Changes from the old system...

A better menu system.
Uses CSS's '<' selector in Firefox and unobtrusive JavaScript in IE. I used the Suckerfish dropdown scirpt to create the menu.
CSS layout - 3 column fluid layout.
I think I am getting the hang of CSS layout - it was much easier this time than when I did the same for the blog.
Ajaxed Feedback Forms
The example from my Ajax Tutorial have been implemented in the new site - with PHP/MySQL backend. The old system had a Perl/Text File backend(in Tripod).
PHP based
The old system was a completely static site - just HTML, JavaScript and CSS - I had no other option. Now that I have PHP, I could do a lot more damage.
More Problems
The old system is a tired and true system - the new system still has a lot of broken links, missing pages, script errors and what not. These problem have to be ironed out - I am waiting for user responses for this one.
Old content deleted.
Some very old pages are not included in the new site.
And More...
Not all the changes can be listed here - why don't you visit the site and find out for yourself?

Filed Under...


JavaScirpt Tutorial by Simon Willson

Simon Willson, a developer at Yahoo have created a presentation called A (Re)-Introduction to JavaScript. It is a very good introduction to javascript - and since it is in slide show format it is very easy to read.

If you don't know JavaScript, please go read it. If you know javascript, please go read it(he did'nt call it Re-Introduction without a reason). There is 111 slides - so it will take some time to read the full tutorial - but is it worth it. But then, I took a lot of time to read it not because it had a lot of text - but I had a slow connection and I had to download all the images one page at a time.


Low Quality but Faster Slides
High Quality copy of the Slides at Flicker
HTML Version of the Slides

One feature of javascript that I have yet not used was given in this slide show - the short-circuit logic.

The && and || operators use short-circuit logic, which means they will execute their second operand dependant on the first. This is useful for checking for null objects before accessing their attributes:
var name = o && o.getName();
Or for setting default values:
var name = otherName || "default";

Now to use it somewhere...


Ajax Feedback Form (Part 3 of the Ajax Tutorial)

In this section we will add ajax functionality to the form we created in the last page. We will try to avoid touching the orginal code as much as possible - using behaviour elements(script) inside the body part is not a good practice.

First we will create a new submit behaviour for the form. By default, the form will submit the data to a different page. We need to change this behaviour so that when the form is submited, a javascript function will be called.

<script language="javascript" type="text/javascript">
//This function will be called when the form is submited
function saveData() {
 // ...

 return false;//Prevent the form from being submited
function init() {
 document.getElementById("feedback_form").onsubmit = saveData; //The saveData function is attached to the submi action of the form. 
window.onload = init; //The 'init' function will be called when the page is loaded.

Put this code in the head part of the page. Now nothing will happen when you click the submit button. JavaScript will call the saveData() function - but since it does nothing, the user will not see any change in the page if the submit button is clicked. The return false; will prevent the form from being submited. The next step is to add the Ajax functionality to our page. For that I will use my 'jx' ajax functions. This is the simpilest library - just 50 lines of code. This library has its limitations but for the present application it will do. There are many other Ajax libraries available in the net.

We need a new javascript file with the name 'jx_lib.js' with the following content...

/////////////////////////////////// ax Ajax Library Functions /////////////////////////////////
var jx_http = jx_getHTTPObject(); // We create the HTTP Object
//Create a xmlHttpRequest object - this is the constructor. 
function jx_getHTTPObject() {
 var xmlhttp;

 //Use IE's ActiveX items to load the file.
 if(typeof ActiveXObject != 'undefined') {
  try {
   xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
   try {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (E) {
    xmlhttp = false;
 //If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
 } else if (XMLHttpRequest) {
  try {
   xmlhttp = new XMLHttpRequest();
  } catch (e) {
   xmlhttp = false;
 } else {
  xmlhttp = false;
 return xmlhttp;

//This function is called from the user's script. It will take a url and an optional callback function.
// Then it will read the url file, expecting a json string. Once the file is loaded, the script
// will pharse the json string using 'eval' and call the user defined callback function with this
// array as the argument.
//Arguments - 
// url - The url of the serverside script that is to be called. Append all the arguments to 
//   this urls as GET params - like get_data.php?id=5&car=benz
// callback - Name of the function that should be called once the data is ready. If a callback
//   function is not given, then the default function 'jx_processResults' will be used.
function jx_getData(url,callback) {
 if(!jx_http) return;"GET", url, true); 

 //Call a anonymos function when the state changes.
 jx_http.onreadystatechange = function () {
  if (jx_http.readyState == 4) {//Ready State will be 4 when the document is loaded.
   var result;
   if(jx_http.responseText) result = eval(jx_http.responseText); //Yes, I know I used eval - its JSON, stupid.
   else result = "";

   if(callback) {
    callback(result); //Give the data to the user defined function.
   } else { //If there is no user defined function...
    //Call a predifined  function with the result.
    if(jx_processResults) jx_processResults(result);

In our HTML file(the file containing the Feedback form, put the following code in the head section.

<script language="javascript" type="text/javascript" src="jx_lib.js"></script>
<script language="javascript" type="text/javascript">
//This function will be called when the form is submited
function saveData() {
 // ...

 return false;//Prevent the form from being submited
function init() {
 if(jx_http) {//If the browser supports Ajax functions
  document.getElementById("feedback_form").onsubmit = saveData; //The saveData function is attached to the submit action of the form.
window.onload = init; //The 'init' function will be called when the page is loaded.

The first line will include the ajax library functions. Don't worry about what the code will do - we will see more about it latter. Just include the code in our page. This will add the necessary ajax functionality to our page - now we must define what must happen when the user clicks the 'Submit' button. Just put the following code inside the 'saveData()' function.

//This function will be called when the form is submited
function saveData() {
 var comment = document.getElementById("comment").value;
 var email = document.getElementById("email").value;

 //By calling this file, we have saved the data.
 jx_getData("save_data.php?comment=" + comment + "&email=" + email + "&return=none");
 //Display the thank you message.
 document.getElementById("form_elements").innerHTML = "<h1>Feedback Recived</h1>Thank you for your intrest - we will look into your comment as soon as possible.";
 return false;//Prevent the form from being submited

This will pass the data to the 'save_data.php' PHP file that will insert the values into the database. The code used in the php file must be changed a bit to accomodate this. In the traditional way, the PHP will print out a thank you message - but in the Ajax method we do not need this. So we will have to disable this in ajax mode. Notice the argument &return=none in the line
jx_getData("save_data.php?comment=" + comment + "&email=" + email + "&return=none");
We will check for this argument in the PHP file - if we find this argument present, we will return without displaying anything. Else we will show the full thank you note. For this effect we will modify the PHP file thus...

include('./connect.php'); //Connect to the database.

//Insert data into our database
mysql_query("INSERT INTO feedback(feedback_email,feedback_comment,feedback_time) 
 VALUES('$_REQUEST[email]','$_REQUEST[comment]',NOW())") or die("Cannot save : " . mysql_error());

if($_REQUEST['return'] == 'none') exit; //Exit without printing the Thank you note.

<title>Feedback Recived</title>
<h1>Feedback Recived</h1>

Thank you for your intrest - we will look into your comment as soon as possible.


We are done. Now the Ajax Feedback form is fully functional. If the user's browser has JavaScript capability, the user will experiance the full effect of ajax. If they are using an old browser, our progam will still work - but in the traditional way - without any bells and whistles.

Read More... Transaction Status

The transaction from my old site to my new site is going smoothly. Some major work remains to be done - this is not a very daunting task - I just have to convert all my pages from static text to dynamic PHP script. Just brainless manual labor - but I hate doing it. I am hoping to complete all works by the 15th of this month.

As expected there are some troubles - the major one being SEO. Almost all the SEO work I have done till date is aimed at my geocities site. So all the advantage gained there will be lost when I make the transition. The good news is that Google have already recognized my main page. Search for "" in google and you will get my new site as the result. The bad news is that only one page is index as of yet. Still I guess it is good for a 3 day old site.

The next thing is all the links I have collected over the years. Many sites have linked to my old site. All the visitors must be redirected to the new site once the work is complete - this won't be much of a problem as I have already created a script that will redirect the user to the same page in the new site. Go to my Tcl/Tk Tutorial page and click on any link to see the result of this script. I have not enabled this script globally - but I will do that once the work is over.

The script is given here...

//Redirect user to the same page on another server 
function redirect() {
  var anchors = document.getElementsByTagName('a');
  for (var i=0;i<anchors.length;i++) {
    var href = anchors[i].getAttribute('href');
    var old_location = "";

    if(href.indexOf(old_location) != -1) { //Change only the internal links - leaves the external links
      href = href.replace(old_location,"");
      anchors[i].href = "" + href;

      //Not really necessary - I had to add this because I used geocities
   //    and they inserted frames all over the place
      anchors[i].onclick = function () {
       parent.location.href = "" + href;

The third problem is the design. The old design was good for a geocities site - but it is just not professional enough for a web development site. I will have to get better design - and I am very bad at designing. I mean, most of my 'designs' look like a 4-year old kid's mis-adventures with a crayon.

Filed Under...

Read More... - A domain to call my own

Finally, after much frustration I have got my hands on my own domain and web space. is mine - along with 500 MB space and 25 GB transfer per month, PHP hosting with 10 MySQL database limit. Almost everything I needed. I have bought it from yesterday. I have already begun the exodus from my earlier hosts to my new site. This will take some time - but it is definitely worth it.

Finally I could say goodbye to free services like Geocities and Tripod. I have been depending on these services for far too long. These sites are good if you are just creating a small 2-3 pages site. But if you are depending on it to create bigger site, you are making a big mistake. The servers of these site actively change to code on our pages to insert their ads. If you invested a large amount of time to create XHTML valid site, you are going to be very surprised - I know - I have tried it.

Don't get me wrong - I am very grateful to these services. Had it not been for these free sites, I would never have hosted my first website. It was at another 'free' server - BizLand. Now that site is dead and gone. After bizland I moved to Tripod at When tripod brought contextual ads to their site, my site became very slow - so I moved to GeoCities. That have been my home till now. After about 5 to 6 years of working on my site, it moving to its own domain - one I hope would be its last.

The different servers I depended on through the years are listed below...

Some highlights of the new site...

Tcl/Tk Tutorial
A highly rated tutorial for Tcl/Tk - a simple GUI creating language. One of my best tutorials.
Perl/Tk Tutorial
A easy to follow tutorial for the Tk module of Perl. Based on the Tcl/Tk tutorial.
Perl Tutorial for CGI
Beginners Perl Tutorial. Focuses on the CGI(Common Gateway Interface) section of perl.
JavaScript Basic Tutorial
An interactive Tutorial of JavaScript for beginners. This is somewhat old.
JavaScript Advanced Tutorial
Another interactive Tutorial for JavaScript on more advanced issues. This also is kind of old and must be rewritten.
Programs Database
A XML database of all the programs I have written.
Online Sudoku
A javascript version of the popular japanese number game sudoku. One of the most popular pages of the site.

More about the new site later...

Filed Under...


Subscribe to : Posts