Perl5 には標準で用意されている CGI.pm を利用すれば、 複雑な(簡単な)CGI でもすぐ作れてしまいます。 標準で利用できるライブラリなので、この XREA でも 使えます。
まずは Hello, world! プログラムです。ところで、世界で 一番最初に Hello, world! を書いた人は誰で、言語は 何(まあ、アセンブラかな?)だったのでしょう? だれか知っている人、教えてください。
#!/usr/bin/perl # use strict; use warnings; use CGI; my $query = new CGI; print $query->header; print $query->start_html; print $query->p("Hello, world!"); print $query->end_html;
以上です。出力結果は、下のようになります。
Content-Type: text/html; charset=ISO-8859-1 <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"><head><title>Untitled Document</title> </head><body><p>Hello, world!</p></body></html>
各関数の役割は、関数名からあきらかですが、以下の通りです。
要は、書き出したい内容を start_html と end_html の間に書き出してやれば よいのです。
:html2 h1 ... h6 p br hr ol ul li dl dt dd menu code var strong em tt u i b blockquote pre img a address cite samp dfn html head base body Link nextid title meta kbd start_html end_html input Select option comment charset escapeHTML :html3 div table caption th td TR Tr sup Sub strike applet Param embed basefont style span layer ilayer font frameset frame script small big :netscape blink fontsize center :form textfield textarea filefield password_field hidden checkbox checkbox_group submit reset defaults radio_group popup_menu button autoEscape scrolling_list image_button start_form end_form startform endform start_multipart_form end_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART :cgi param upload path_info path_translated url self_url script_name cookie Dump raw_cookie request_method query_string Accept user_agent remote_host content_type remote_addr referer server_name server_software server_port server_protocol virtual_host remote_ident auth_type http save_parameters restore_parameters param_fetch remote_user user_name header redirect import_names put Delete Delete_all url_param cgi_error :ssl https :imagemap Area Map :cgi-lib ReadParse PrintHeader HtmlTop HtmlBot SplitParam Vars :push multipart_init multipart_start multipart_end multipart_final
POST を用いたファイルのアップロードプログラムも簡単です。
#!/usr/bin/perl use strict; use warnings; use CGI; my $q = new CGI; my $fh; print $q->header, $q->start_html('File Uploader'), $q->h1('File Uploader'), $q->start_multipart_form, $q->filefield( -name => 'uploaded_file', -default => 'starting value', -size => 50, -maxlength => 80 ), $q->submit, $q->end_form; $fh = $q->upload('uploaded_file'); if ($fh) { $fh =~ /([^\\\/]*)$/; my $file = $1; my $buffer; print "uploaded $file", $q->br; open(OUT, "> $file"); while (read($fh, $buffer, 1024)) { print OUT $buffer; } close(OUT); close($fh); } print $q->end_html;