Sunday, October 20, 2019
Hello World CGI Script in Perl
Hello World CGI Script in Perl A CGI script can be as simple or complex as you need it to be. It could be in Perl, Java, Python or any programming language. At its core, a CGI application simply takes a request via HTTP (typically a web browser) and returns HTML. Lets look at a simple Perlà Hello World CGI script and break it down into its simplest forms. Hello World CGI Perl Script #!/usr/bin/perl print Content-type: text/html\n\n; print HTML; html head titleA Simple Perl CGI/title /head body h1A Simple Perl CGI/h1 pHello World/p /body HTML exit; If you run the program on the command line, youll see that it does exactly what youd expect. First, it prints the Content-type line, then it prints the raw HTML. In order to see it in action in a web browser, youll need to copy or upload the script to your web server and make sure the permissions are set correctly (chmod 755 on *nix systems). Once youve set it correctly, you should be able to browse to it and see the page displayed live on your server. The key line is the first print statement: print Content-type: text/html\n\n; This tells the browser that the document coming after the two newlines is going to be HTML. You must send a header so the browser knows what type of document is coming next, and you must include a blank line between the header and the actual document. Once the header is sent, its just a matter of sending the HTML document itself. In the above example, were using a here-doc to simplify printing a large chunk of plain text. Of course, this is really no different than having a plain HTML document sitting on your server. The real power of using a programming language like Perl to create your HTML comes when you add in some fancy Perl programming. Adding on to the Basic Script In the next example, lets take part of thisà time and date script and add it to your web page. #!/usr/bin/perl months qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); weekDays qw(Sun Mon Tue Wed Thu Fri Sat Sun); ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) localtime(); $year 1900 $yearOffset; $theTime $weekDays[$dayOfWeek] $months[$month] $dayOfMonth, $year; print Content-type: text/html\n\n; print HTML; html head titleA Simple Perl CGI/title /head body h1A Simple Perl CGI/h1 p$theTime/p /body HTML exit; This new CGI script will insert the current date into the page each time the script is called. In other words, it becomes a dynamic document that changes as the date changes, rather than a static document.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.