Home > Article > Backend Development > How to create a simple Perl CGI
CGI scripts can be simple or complex. It can be Perl, Java, Python or any programming language. At its core, a CGI application simply accepts requests over HTTP (usually a web browser) and returns HTML. Let's take a simple Perl Hello World CGI script and break it down to its simplest form.
'Hello World' CGI Perl Script
#!/usr/bin/perl print "Content-type: text/html\n\n"; print <<HTML; <html> <head> <title>A Simple Perl CGI</title> </head> <body> <h1>A Simple Perl CGI</h1> <p>Hello World</p> </body> HTML exit;
If you run this program on the command line you will see that it does exactly what you what is expected. First, it prints the content-type line, then the raw HTML. In order to see it in action in a web browser, you need to copy or upload the script to the web server and make sure the permissions are set correctly (chmod 755 on *nix systems). Once it's set up correctly, you should be able to browse to it and see the page live on the server.
The key line is the first print statement:
print "Content-type: text/html\n\n";
This tells the browser that the document after these two line breaks will 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.
After sending the header, you only need to send the HTML document itself. In the above example, we use here-doc to simplify printing a large block of plain text. Of course, this is no different than having a plain HTML document on the server. The real power of using a programming language like Perl to create HTML comes when you add in some fancy Perl programming.
Add to Basic Script
In the next example, let's take part of this time and date script and add it to a 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 <A Simple Perl CGI A Simple Perl CGI
$theTime
HTML exit;
This new CGI script will insert the current date into the page every time the script is called. In other words, it becomes a dynamic document that changes as the date changes, rather than a static document.
The above is the detailed content of How to create a simple Perl CGI. For more information, please follow other related articles on the PHP Chinese website!