Tuesday, August 13, 2013

Tips on Converting Python-CGI to Perl-CGI

Last month I created a new feedback page for my personal website, using Python. It worked well on my desktop but when I uploaded it to Tripod, I realized that they support only Perl and not Python. So I decided to convert the feedback page to Perl, without having to recode it from scratch. The groundwork for this took some time, as I had to install Active Perl and brush up my Perl knowledge by tweaking a few old Perl-CGI scripts. Today I created a copy of the CGI script and made the below changes to convert it from Python to Perl. Hope these tips would be useful to someone who reads this post.

* Converted the shebang line from #!/Python27/python to #!/Perl/bin/perl
* Added a semi-colon after every line of Python (now Perl) code
* Added a $ sign before every Python (now Perl) scalar variable
* Converted the multi-line prints from Python format (print """) to Perl format (print <<HTML)
* Removed the Python import line for "sys"
* Removed the Python import line for "time". Used Perl's localtime() function to get date and time
* Removed the Python import line for "cgi". Used a downloaded Perl code snippet to get the CGI parameters, choosing  one that takes care of both GET and POST parameters
* Converted the Python "if-elif-else" syntax to the equivalent Perl "if-elsif-else" syntax
* Converted the Python "try-except" code for opening a text file to the normal Perl file opening code, as Perl does not currently support "try-except"
* Converted the single-line file open and read code of Python to the equivalent Perl code
* Converted the Python syntax [filename.write("abc")] for writing to text file to the equivalent Perl syntax [print FILENAME "abc"]
* Replaced Python's text concatenation operator "+" with the equivalent Perl operator "."
* Removed Python's str() function, as Perl automatically takes care of converting variables based on the context
* Ensured use of "eq" operator instead of "==" operator in "if" conditions involving string variables

No comments:

Post a Comment