argra****@users*****
argra****@users*****
2008年 4月 18日 (金) 02:35:43 JST
Index: docs/perl/5.10.0/perlfaq9.pod diff -u /dev/null docs/perl/5.10.0/perlfaq9.pod:1.1 --- /dev/null Fri Apr 18 02:35:43 2008 +++ docs/perl/5.10.0/perlfaq9.pod Fri Apr 18 02:35:43 2008 @@ -0,0 +1,1483 @@ +=head1 NAME + +=begin original + +perlfaq9 - Networking ($Revision: 8539 $) + +=end original + +perlfaq9 - ネットワーク ($Revision: 8539 $) + +=head1 DESCRIPTION + +=begin original + +This section deals with questions related to networking, the internet, +and a few on the web. + +=end original + +このセクションでは、ネットワーク、インターネット、web に関する +質問を扱っています。 + +=head2 What is the correct form of response from a CGI script? + +(CGI スクリプトからの返答の正しい形は?) + +=begin original + +(Alan Flavell <flave****@a5*****> answers...) + +=end original + +(Alan Flavell <flave****@a5*****> が答えます...) + +=begin original + +The Common Gateway Interface (CGI) specifies a software interface between +a program ("CGI script") and a web server (HTTPD). It is not specific +to Perl, and has its own FAQs and tutorials, and usenet group, +comp.infosystems.www.authoring.cgi + +=end original + +The Common Gateway Interface (CGI) はプログラム("CGI スクリプト")と +web サーバ (HTTPD) の間のソフトウェアインターフェースを定めています。 +これは Perl 固有のものではないので、独自の FAQと独自のチュートリアル、 +そして独自の usenet group である comp.infosystems.www.authoring.cgi が +あります。 + +=begin original + +The CGI specification is outlined in an informational RFC: +http://www.ietf.org/rfc/rfc3875 + +=end original + +CGI 仕様は RFC に概要が述べられています: +http://www.ietf.org/rfc/rfc3875 + +=begin original + +Other relevant documentation listed in: http://www.perl.org/CGI_MetaFAQ.html + +=end original + +その他の関連する文書のリストは http://www.perl.org/CGI_MetaFAQ.html に +あります。 + +=begin original + +These Perl FAQs very selectively cover some CGI issues. However, Perl +programmers are strongly advised to use the CGI.pm module, to take care +of the details for them. + +=end original + +These Perl FAQs very selectively cover some CGI issues. However, Perl +programmers are strongly advised to use the CGI.pm module, to take care +of the details for them. +(TBT) + +=begin original + +The similarity between CGI response headers (defined in the CGI +specification) and HTTP response headers (defined in the HTTP +specification, RFC2616) is intentional, but can sometimes be confusing. + +=end original + +The similarity between CGI response headers (defined in the CGI +specification) and HTTP response headers (defined in the HTTP +specification, RFC2616) is intentional, but can sometimes be confusing. +(TBT) + +=begin original + +The CGI specification defines two kinds of script: the "Parsed Header" +script, and the "Non Parsed Header" (NPH) script. Check your server +documentation to see what it supports. "Parsed Header" scripts are +simpler in various respects. The CGI specification allows any of the +usual newline representations in the CGI response (it's the server's +job to create an accurate HTTP response based on it). So "\n" written in +text mode is technically correct, and recommended. NPH scripts are more +tricky: they must put out a complete and accurate set of HTTP +transaction response headers; the HTTP specification calls for records +to be terminated with carriage-return and line-feed, i.e ASCII \015\012 +written in binary mode. + +=end original + +The CGI specification defines two kinds of script: the "Parsed Header" +script, and the "Non Parsed Header" (NPH) script. Check your server +documentation to see what it supports. "Parsed Header" scripts are +simpler in various respects. The CGI specification allows any of the +usual newline representations in the CGI response (it's the server's +job to create an accurate HTTP response based on it). So "\n" written in +text mode is technically correct, and recommended. NPH scripts are more +tricky: they must put out a complete and accurate set of HTTP +transaction response headers; the HTTP specification calls for records +to be terminated with carriage-return and line-feed, i.e ASCII \015\012 +written in binary mode. +(TBT) + +=begin original + +Using CGI.pm gives excellent platform independence, including EBCDIC +systems. CGI.pm selects an appropriate newline representation +($CGI::CRLF) and sets binmode as appropriate. + +=end original + +CGI.pm を使うことで、EBCDIC システムを含むすばらしいプラットフォーム +独立性が得られます。 +CGI.pm は適切な改行表現を選択し($CGI::CRLF)、binmode を適切にセットします。 + +=head2 My CGI script runs from the command line but not the browser. (500 Server Error) + +(私の CGI スクリプトはコマンドラインでは動くのだけど、ブラウザ上では動きません +(500 Server Error になります)) + +=begin original + +Several things could be wrong. You can go through the "Troubleshooting +Perl CGI scripts" guide at + +=end original + +可能性はいくつかあります。 +以下にある "Troubleshooting Perl CGI scripts" ガイドを読みましょう: + + http://www.perl.org/troubleshooting_CGI.html + +=begin original + +If, after that, you can demonstrate that you've read the FAQs and that +your problem isn't something simple that can be easily answered, you'll +probably receive a courteous and useful reply to your question if you +post it on comp.infosystems.www.authoring.cgi (if it's something to do +with HTTP or the CGI protocols). Questions that appear to be Perl +questions but are really CGI ones that are posted to comp.lang.perl.misc +are not so well received. + +=end original + +その後、FAQ を読んで、あなたの問題が簡単に答られるものではないと +わかったのなら、(HTTP や CGI プロトコルに関するものなら) +comp.infosystems.www.authoring.cgi にポストすれば有用なリプライが +得られるでしょう。 +Perl に関する質問のように見えていても、実は CGI に関するものだというものが +comp.lang.perl.misc に投稿されることがありますが、回答はついていません。 + +=begin original + +The useful FAQs, related documents, and troubleshooting guides are +listed in the CGI Meta FAQ: + +=end original + +便利な FAQ、関連するドキュメント、トラブルシューティングガイドは +CGI Meta FAQ に挙げられています: + + http://www.perl.org/CGI_MetaFAQ.html + +=head2 How can I get better error messages from a CGI program? + +(CGI プログラムから、もっとまともなエラーメッセージを得るには?) + +=begin original + +Use the CGI::Carp module. It replaces C<warn> and C<die>, plus the +normal Carp modules C<carp>, C<croak>, and C<confess> functions with +more verbose and safer versions. It still sends them to the normal +server error log. + +=end original + +CGI::Carp モジュールを使いましょう。 +このモジュールは C<warn> と C<die> の置き換えを行い、さらに通常の +Carp モジュールの C<carp>、C<croak>、C<confess> といった関数をより饒舌で +安全なものに置き換えます。 +その出力は、サーバーの通常のエラーログに送られます。 + + use CGI::Carp; + warn "This is a complaint"; + die "But this one is serious"; + +=begin original + +The following use of CGI::Carp also redirects errors to a file of your choice, +placed in a BEGIN block to catch compile-time warnings as well: + +=end original + +以下の CGI::Carp の使用例では、エラーをあなたの選択したファイルへ +リダイレクトし、コンパイル時の警告も同様に補足するため BEGIN ブロックに +置いています: + + BEGIN { + use CGI::Carp qw(carpout); + open(LOG, ">>/var/local/cgi-logs/mycgi-log") + or die "Unable to append to mycgi-log: $!\n"; + carpout(*LOG); + } + +=begin original + +You can even arrange for fatal errors to go back to the client browser, +which is nice for your own debugging, but might confuse the end user. + +=end original + +深刻なエラーをクライアントのブラウザに戻すように変更することもできます。 +これはあなたがデバッグするには良いでしょうが、エンドユーザーを +混乱させてしまうかもしれません。 + + use CGI::Carp qw(fatalsToBrowser); + die "Bad error here"; + +=begin original + +Even if the error happens before you get the HTTP header out, the module +will try to take care of this to avoid the dreaded server 500 errors. +Normal warnings still go out to the server error log (or wherever +you've sent them with C<carpout>) with the application name and date +stamp prepended. + +=end original + +あなたが HTTP ヘッダーを受け取るよりも前にエラーが起こったとしても、 +モジュールはサーバーの 500 エラーを避けるためにそのエラーを取り扱おうと +するでしょう。 +通常の警告はサーバーのエラーログ(もしくはあなたが C<carpout> で指定した場所)に +アプリケーションの名前と日付を伴って送られます。 + +=head2 How do I remove HTML from a string? + +(ある文字列から HTML を取り除くには?) + +=begin original + +The most correct way (albeit not the fastest) is to use HTML::Parser +from CPAN. Another mostly correct +way is to use HTML::FormatText which not only removes HTML but also +attempts to do a little simple formatting of the resulting plain text. + +=end original + +(最速ではありませんが)最も正しい方法は、CPAN にある HTML::Parser を +使うというものです。 +もう一つのまず正しい方法は、HTML::FormatText を使って HTML を +取り除くだけでなく、結果のプレーンテキストを簡単に整形することです。 + +=begin original + +Many folks attempt a simple-minded regular expression approach, like +C<< s/<.*?>//g >>, but that fails in many cases because the tags +may continue over line breaks, they may contain quoted angle-brackets, +or HTML comment may be present. Plus, folks forget to convert +entities--like C<<> for example. + +=end original + +多くの人が、C<< s/<.*?>//g >> のような単純な(simple-minded)正規表現を +使ったアプローチを行おうとするのですが、これは多くの場合 +失敗していまいます。 +なぜなら、タグは行をまたがって継続する可能性があり、 +クォートされたアングルブラケットを含む可能性があり、 +HTML のコメントがあるかもしれないからです。 +さらに、人々は C<<> のようなエンティティを変換することを忘れてしまうのです。 + +=begin original + +Here's one "simple-minded" approach, that works for most files: + +=end original + +以下の例は “単純な”アプローチで、ほとんどのファイルに対しては +うまくいきます: + + #!/usr/bin/perl -p0777 + s/<(?:[^>'"]*|(['"]).*?\1)*>//gs + +=begin original + +If you want a more complete solution, see the 3-stage striphtml +program in +http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz +. + +=end original + +もし、より完璧な解決策を求めているのなら、 +http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz +にある 3-stage striphtml プログラムを参照してみてください。 + +=begin original + +Here are some tricky cases that you should think about when picking +a solution: + +=end original + +以下に挙げたのは、あなたが自分でやろうとしたときに +考慮すべきであろうトリッキーな例です: + + <IMG SRC = "foo.gif" ALT = "A > B"> + + <IMG SRC = "foo.gif" + ALT = "A > B"> + + <!-- <A comment> --> + + <script>if (a<b && a>c)</script> + + <# Just data #> + + <![INCLUDE CDATA [ >>>>>>>>>>>> ]]> + +=begin original + +If HTML comments include other tags, those solutions would also break +on text like this: + +=end original + +以下のテキストのように HTML のコメントが他のタグを含んでいた場合には、 +せっかくの対応策もダメにしてしまうかもしれません: + + <!-- This section commented out. + <B>You can't see me!</B> + --> + +=head2 How do I extract URLs? + +(URL の展開を行うには?) + +=begin original + +You can easily extract all sorts of URLs from HTML with +C<HTML::SimpleLinkExtor> which handles anchors, images, objects, +frames, and many other tags that can contain a URL. If you need +anything more complex, you can create your own subclass of +C<HTML::LinkExtor> or C<HTML::Parser>. You might even use +C<HTML::SimpleLinkExtor> as an example for something specifically +suited to your needs. + +=end original + +You can easily extract all sorts of URLs from HTML with +C<HTML::SimpleLinkExtor> which handles anchors, images, objects, +frames, and many other tags that can contain a URL. If you need +anything more complex, you can create your own subclass of +C<HTML::LinkExtor> or C<HTML::Parser>. You might even use +C<HTML::SimpleLinkExtor> as an example for something specifically +suited to your needs. +(TBT) + +=begin original + +You can use URI::Find to extract URLs from an arbitrary text document. + +=end original + +任意のテキスト文書から URL を抽出するためには、URI::Find が使えます。 + +=begin original + +Less complete solutions involving regular expressions can save +you a lot of processing time if you know that the input is simple. One +solution from Tom Christiansen runs 100 times faster than most +module based approaches but only extracts URLs from anchors where the first +attribute is HREF and there are no other attributes. + +=end original + +Less complete solutions involving regular expressions can save +you a lot of processing time if you know that the input is simple. One +solution from Tom Christiansen runs 100 times faster than most +module based approaches but only extracts URLs from anchors where the first +attribute is HREF and there are no other attributes. +(TBT) + + #!/usr/bin/perl -n00 + # qxurl - tchri****@perl***** + print "$2\n" while m{ + < \s* + A \s+ HREF \s* = \s* (["']) (.*?) \1 + \s* > + }gsix; + +=head2 How do I download a file from the user's machine? How do I open a file on another machine? + +(ユーザーのマシンからファイルをダウンロードするには? 別のマシンにあるファイルをオープンするには?) + +=begin original + +In this case, download means to use the file upload feature of HTML +forms. You allow the web surfer to specify a file to send to your web +server. To you it looks like a download, and to the user it looks +like an upload. No matter what you call it, you do it with what's +known as B<multipart/form-data> encoding. The CGI.pm module (which +comes with Perl as part of the Standard Library) supports this in the +start_multipart_form() method, which isn't the same as the startform() +method. + +=end original + +In this case, download means to use the file upload feature of HTML +forms. You allow the web surfer to specify a file to send to your web +server. To you it looks like a download, and to the user it looks +like an upload. +何と呼ぶかには関わらず、B<multipart/form-data> +エンコーディングとして知られているものを使うことができるでしょう。 +CGI.pm モジュール(標準ライブラリになっています)はこれを start_multipart_form() +という starform() メソッドとは異なるメソッドでサポートしています。 +(TBT) + +=begin original + +See the section in the CGI.pm documentation on file uploads for code +examples and details. + +=end original + +コードのサンプルと詳細については、CGI.pm の文書のファイルアップロードの +章を参照してください。 + +=head2 How do I make an HTML pop-up menu with Perl? + +(Perl で HTML のポップアップメニューを作るには?) + +=begin original + +(contributed by brian d foy) + +=end original + +(brian d foy によって寄贈されました) + +=begin original + +The CGI.pm module (which comes with Perl) has functions to create +the HTML form widgets. See the CGI.pm documentation for more +examples. + +=end original + +CGI.pm モジュール(標準配布です)には HTML フォームウィジェットを作るための +関数があります。 +更なる例については CGI.pm の文書を参照してください。 + + use CGI qw/:standard/; + print header, + start_html('Favorite Animals'), + + start_form, + "What's your favorite animal? ", + popup_menu( + -name => 'animal', + -values => [ qw( Llama Alpaca Camel Ram ) ] + ), + submit, + + end_form, + end_html; + +=head2 How do I fetch an HTML file? + +(HTML ファイルをフェッチするには?) + +=begin original + +One approach, if you have the lynx text-based HTML browser installed +on your system, is this: + +=end original + +一つのやり方は、あなたが lynx というテキストベースの HTML ブラウザを +インストールしているとすれば、次のようなものです: + + $html_code = `lynx -source $url`; + $text_data = `lynx -dump $url`; + +=begin original + +The libwww-perl (LWP) modules from CPAN provide a more powerful way +to do this. They don't require lynx, but like lynx, can still work +through proxies: + +=end original + +CPAN で入手できる libwww-perl (LWP) モジュールはこれを行う、 +よりパワフルな方法を提供します。 +これは lynx を必要とせず、プロキシ越しでも使えます: + + # simplest version + use LWP::Simple; + $content = get($URL); + + # or print HTML from a URL + use LWP::Simple; + getprint "http://www.linpro.no/lwp/"; + + # or print ASCII from HTML from a URL + # also need HTML-Tree package from CPAN + use LWP::Simple; + use HTML::Parser; + use HTML::FormatText; + my ($html, $ascii); + $html = get("http://www.perl.com/"); + defined $html + or die "Can't fetch HTML from http://www.perl.com/"; + $ascii = HTML::FormatText->new->format(parse_html($html)); + print $ascii; + +=head2 How do I automate an HTML form submission? + +(HTML フォームの処理を自動化するには?) + +=begin original + +If you are doing something complex, such as moving through many pages +and forms or a web site, you can use C<WWW::Mechanize>. See its +documentation for all the details. + +=end original + +If you are doing something complex, such as moving through many pages +and forms or a web site, you can use C<WWW::Mechanize>. See its +documentation for all the details. +(TBT) + +=begin original + +If you're submitting values using the GET method, create a URL and encode +the form using the C<query_form> method: + +=end original + +GET メソッドを使って値を処理しているのであれば、URL を作って、 +さらに C<query_form> メソッドを使ってフォームをエンコードします: + + use LWP::Simple; + use URI::URL; + + my $url = url('http://www.perl.com/cgi-bin/cpan_mod'); + $url->query_form(module => 'DB_File', readme => 1); + $content = get($url); + +=begin original + +If you're using the POST method, create your own user agent and encode +the content appropriately. + +=end original + +POST メソッドを使っているのであれば、自分用のエージェントを作成して +コンテンツを適切にエンコードしてやります。 + + use HTTP::Request::Common qw(POST); + use LWP::UserAgent; + + $ua = LWP::UserAgent->new(); + my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod', + [ module => 'DB_File', readme => 1 ]; + $content = $ua->request($req)->as_string; + +=head2 How do I decode or create those %-encodings on the web? + +(web上で %-encodings をデコードしたり生成したりするには?) + +=begin original + +If you are writing a CGI script, you should be using the CGI.pm module +that comes with perl, or some other equivalent module. The CGI module +automatically decodes queries for you, and provides an escape() +function to handle encoding. + +=end original + +CGI スクリプトを書いているのなら、perl に付属している CGI.pm モジュール +または等価なモジュールを使うべきです。 +CGI モジュールは自動的にクエリをデコードし、escape() 関数で +エンコードもできます。 + +=begin original + +The best source of detailed information on URI encoding is RFC 2396. +Basically, the following substitutions do it: + +=end original + +URI エンコーディングの詳細情報に関する最良のソースは RFC 2396 です。 +基本的には、以下の置換が実行されます: + + s/([^\w()'*~!.-])/sprintf '%%%02x', ord $1/eg; # encode + + s/%([A-Fa-f\d]{2})/chr hex $1/eg; # decode + s/%([[:xdigit:]]{2})/chr hex $1/eg; # same thing + +=begin original + +However, you should only apply them to individual URI components, not +the entire URI, otherwise you'll lose information and generally mess +things up. If that didn't explain it, don't worry. Just go read +section 2 of the RFC, it's probably the best explanation there is. + +=end original + +しかし、これは URI 全体ではなく、個々の URI コンポーネントに +対して適用するべきです。 +さもなければ、情報が失われ、ぐちゃぐちゃになります。 +これが説明になっていなくても、心配はいりません。 +RFC の第 2 章を読んでください。 +おそらくこの問題に関する最良の説明です。 + +=begin original + +RFC 2396 also contains a lot of other useful information, including a +regexp for breaking any arbitrary URI into components (Appendix B). + +=end original + +RFC 2396 にはその他の有用な情報が多く含まれています。 +その中には任意の URI をコンポーネントに分割するための +正規表現 (Appendix B) を含みます。 + +=head2 How do I redirect to another page? + +(別のページにリダイレクトするには?) + +=begin original + +Specify the complete URL of the destination (even if it is on the same +server). This is one of the two different kinds of CGI "Location:" +responses which are defined in the CGI specification for a Parsed Headers +script. The other kind (an absolute URLpath) is resolved internally to +the server without any HTTP redirection. The CGI specifications do not +allow relative URLs in either case. + +=end original + +Specify the complete URL of the destination (even if it is on the same +server). This is one of the two different kinds of CGI "Location:" +responses which are defined in the CGI specification for a Parsed Headers +script. The other kind (an absolute URLpath) is resolved internally to +the server without any HTTP redirection. The CGI specifications do not +allow relative URLs in either case. +(TBT) + +=begin original + +Use of CGI.pm is strongly recommended. This example shows redirection +with a complete URL. This redirection is handled by the web browser. + +=end original + +CGI.pm を使うことを強くお勧めします。 +この例では完全な URL へのリダイレクトを行います。 +このリダイレクトは web ブラウザによって扱われます。 + + use CGI qw/:standard/; + + my $url = 'http://www.cpan.org/'; + print redirect($url); + +=begin original + +This example shows a redirection with an absolute URLpath. This +redirection is handled by the local web server. + +=end original + +この例では絶対 URL パスへのリダイレクトを行います。 +このリダイレクトはローカルの web サーバによって行われます。 + + my $url = '/CPAN/index.html'; + print redirect($url); + +=begin original + +But if coded directly, it could be as follows (the final "\n" is +shown separately, for clarity), using either a complete URL or +an absolute URLpath. + +=end original + +But if coded directly, it could be as follows (the final "\n" is +shown separately, for clarity), using either a complete URL or +an absolute URLpath. +(TBT) + + print "Location: $url\n"; # CGI response header + print "\n"; # end of headers + +=head2 How do I put a password on my web pages? + +(私の web ぺージでパスワードを入力するには?) + +=begin original + +To enable authentication for your web server, you need to configure +your web server. The configuration is different for different sorts +of web servers--apache does it differently from iPlanet which does +it differently from IIS. Check your web server documentation for +the details for your particular server. + +=end original + +To enable authentication for your web server, you need to configure +your web server. The configuration is different for different sorts +of web servers--apache does it differently from iPlanet which does +it differently from IIS. Check your web server documentation for +the details for your particular server. +(TBT) + +=head2 How do I edit my .htpasswd and .htgroup files with Perl? + +(Perl を使って .htpasswd や .htgroup といったファイルを編集するには?) + +=begin original + +The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a +consistent OO interface to these files, regardless of how they're +stored. Databases may be text, dbm, Berkeley DB or any database with +a DBI compatible driver. HTTPD::UserAdmin supports files used by the +"Basic" and "Digest" authentication schemes. Here's an example: + +=end original + +HTTPD::UserAdmin モジュールと HTTPD::GroupAdmin モジュールは、 +ファイルがどのように格納されているかに関係なくこれらのファイルに対する +首尾一貫したオブジェクト指向インターフェースを提供します。 +データベースはテキスト、dbm、Berkeley DB、あるいは DBI 互換ドライバのある +どんなデータベースでもかまいません。 +HTTPD::UserAdmin は "Basic" および "Digest" 認証スキームで +使われるファイルをサポートします。 +以下に例を挙げます: + + use HTTPD::UserAdmin (); + HTTPD::UserAdmin + ->new(DB => "/foo/.htpasswd") + ->add($username => $password); + +=head2 How do I make sure users can't enter values into a form that cause my CGI script to do bad things? + +(私の CGI スクリプトに悪影響をもたらすようなものを、ユーザーがフォームに入力できないようにするには?) + +=begin original + +See the security references listed in the CGI Meta FAQ + +=end original + +See the security references listed in the CGI Meta FAQ +(TBT) + + http://www.perl.org/CGI_MetaFAQ.html + +=head2 How do I parse a mail header? + +(メールのヘッダーを解析するには?) + +=begin original + +For a quick-and-dirty solution, try this solution derived +from L<perlfunc/split>: + +=end original + +拙速な解決策なら、L<perlfunc/split> から派生した +以下のやり方を試してみてください。 + + $/ = ''; + $header = <MSG>; + $header =~ s/\n\s+/ /g; # merge continuation lines + %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header ); + +=begin original + +That solution doesn't do well if, for example, you're trying to +maintain all the Received lines. A more complete approach is to use +the Mail::Header module from CPAN (part of the MailTools package). + +=end original + +このやり方は、たとえば受信した行すべてを保守しようとするときには +うまくありません。 +より完璧なアプローチはCPANにあるMail::Header モジュールを +使うというものです(このモジュールは MailTools パッケージの一部です)。 + +=head2 How do I decode a CGI form? + +(CGI フォームをデコードするには?) + +=begin original + +(contributed by brian d foy) + +=end original + +(brian d foy によって寄贈されました) + +=begin original + +Use the CGI.pm module that comes with Perl. It's quick, +it's easy, and it actually does quite a bit of work to +ensure things happen correctly. It handles GET, POST, and +HEAD requests, multipart forms, multivalued fields, query +string and message body combinations, and many other things +you probably don't want to think about. + +=end original + +Perl に同梱されている CGI.pm モジュールを使いましょう。 +これは早く、簡単で、物事が正しく行われることを確実にするための +ちょっとした作業を行います。 +GET, POST, HEAD リクエスト、マルチパートフォーム、複数値フィールド、 +クエリ文字列とメッセージボディの組み合わせ、およびその他の、 +あなたが考えようとも思わないような多くの事柄を扱えます。 + +=begin original + +It doesn't get much easier: the CGI module automatically +parses the input and makes each value available through the +C<param()> function. + +=end original + +It doesn't get much easier: the CGI module automatically +parses the input and makes each value available through the +C<param()> function. +(TBT) + + use CGI qw(:standard); + + my $total = param( 'price' ) + param( 'shipping' ); + + my @items = param( 'item' ); # multiple values, same field name + +=begin original + +If you want an object-oriented approach, CGI.pm can do that too. + +=end original + +オブジェクト指向な手法が使いたいなら、CGI.pm はそのようにもできます。 + + use CGI; + + my $cgi = CGI->new(); + + my $total = $cgi->param( 'price' ) + $cgi->param( 'shipping' ); + + my @items = $cgi->param( 'item' ); + +=begin original + +You might also try CGI::Minimal which is a lightweight version +of the same thing. Other CGI::* modules on CPAN might work better +for you, too. + +=end original + +You might also try CGI::Minimal which is a lightweight version +of the same thing. Other CGI::* modules on CPAN might work better +for you, too. +(TBT) + +=begin original + +Many people try to write their own decoder (or copy one from +another program) and then run into one of the many "gotchas" +of the task. It's much easier and less hassle to use CGI.pm. + +=end original + +Many people try to write their own decoder (or copy one from +another program) and then run into one of the many "gotchas" +of the task. It's much easier and less hassle to use CGI.pm. +(TBT) + +=head2 How do I check a valid mail address? + +(メールアドレスが正しいかチェックするには?) + +=begin original + +(partly contributed by Aaron Sherman) + +=end original + +(一部は Aaron Sherman によって寄贈されました) + +=begin original + +This isn't as simple a question as it sounds. There are two parts: + +=end original + +これは見た目ほど単純な質問ではありません。 +これは二つの部分からなります: + +=begin original + +a) How do I verify that an email address is correctly formatted? + +=end original + +a) メールアドレスが正しい形式かを検証するには? + +=begin original + +b) How do I verify that an email address targets a valid recipient? + +=end original + +b) メールアドレスが正当な受信者を対象としているかを検証するには? + +=begin original + +Without sending mail to the address and seeing whether there's a human +on the other end to answer you, you cannot fully answer part I<b>, but +either the C<Email::Valid> or the C<RFC::RFC822::Address> module will do +both part I<a> and part I<b> as far as you can in real-time. + +=end original + +そのアドレスにメールを送ってそれが届いたかどうかを確認しなければ +完全にパート I<b> に答えられませんが、 +either the C<Email::Valid> or the C<RFC::RFC822::Address> module will do +both part I<a> and part I<b> as far as you can in real-time. +(TBT) + +=begin original + +If you want to just check part I<a> to see that the address is valid +according to the mail header standard with a simple regular expression, +you can have problems, because there are deliverable addresses that +aren't RFC-2822 (the latest mail header standard) compliant, and +addresses that aren't deliverable which, are compliant. However, the +following will match valid RFC-2822 addresses that do not have comments, +folding whitespace, or any other obsolete or non-essential elements. +This I<just> matches the address itself: + +=end original + +If you want to just check part I<a> to see that the address is valid +according to the mail header standard with a simple regular expression, +you can have problems, because there are deliverable addresses that +aren't RFC-2822 (the latest mail header standard) compliant, and +addresses that aren't deliverable which, are compliant. However, the +following will match valid RFC-2822 addresses that do not have comments, +folding whitespace, or any other obsolete or non-essential elements. +This I<just> matches the address itself: +(TBT) + + my $atom = qr{[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+}; + my $dot_atom = qr{$atom(?:\.$atom)*}; + my $quoted = qr{"(?:\\[^\r\n]|[^\\"])*"}; + my $local = qr{(?:$dot_atom|$quoted)}; + my $domain_lit = qr{\[(?:\\\S|[\x21-\x5a\x5e-\x7e])*\]}; + my $domain = qr{(?:$dot_atom|$domain_lit)}; + my $addr_spec = qr{$local\@$domain}; + +=begin original + +Just match an address against C</^${addr_spec}$/> to see if it follows +the RFC2822 specification. However, because it is impossible to be +sure that such a correctly formed address is actually the correct way +to reach a particular person or even has a mailbox associated with it, +you must be very careful about how you use this. + +=end original + +Just match an address against C</^${addr_spec}$/> to see if it follows +the RFC2822 specification. However, because it is impossible to be +sure that such a correctly formed address is actually the correct way +to reach a particular person or even has a mailbox associated with it, +you must be very careful about how you use this. +(TBT) + +=begin original + +Our best advice for verifying a person's mail address is to have them +enter their address twice, just as you normally do to change a +password. This usually weeds out typos. If both versions match, send +mail to that address with a personal message. If you get the message +back and they've followed your directions, you can be reasonably +assured that it's real. + +=end original + +私たちができる最善のアドバイスは、個人のメールアドレスをチェックするのに +パスワードを変更するときと同じようにユーザーにアドレスを +二回入力させるというものです。 +これによって通常は打ち間違いを防ぐことができます。 +二回の入力がマッチしたなら、個人的な内容のメッセージをメールとして +そのアドレスへ送ります。 +もしメッセージが返ってきて、それがあなたの指示に従っているなら、 +それが実際のものであると十分に仮定できます。 + +=begin original + +A related strategy that's less open to forgery is to give them a PIN +(personal ID number). Record the address and PIN (best that it be a +random one) for later processing. In the mail you send, ask them to +include the PIN in their reply. But if it bounces, or the message is +included via a "vacation" script, it'll be there anyway. So it's +best to ask them to mail back a slight alteration of the PIN, such as +with the characters reversed, one added or subtracted to each digit, etc. + +=end original + +より偽造のやりにくい別のやり方に、チェックに対象者に対して PIN +(Personal ID Number) を与えるというものがあります。 +後の処理のためにアドレスと PIN (ランダムであることが望ましい)を +記録しておくのです。 +あなたがメールを送るときに、宛て先人に対して彼らの出すリプライに +PIN を含めるように依頼するのです。 +しかしそれがそのまま返ってきたり、あるいは返ってきたメッセージが +"vacation" スクリプトを通じてのものであっても、そのまま PIN が +含まれてしまいます。 +ですから、最善なやり方はメールを送るときに返事には文字を逆順にするとか、 +各桁に対して足し算や引き算を行うなどして +PIN を変形したものを含めて返すように依頼するという方法です。 + +=head2 How do I decode a MIME/BASE64 string? + +(MIME/BASE64 文字列のデコードを行うには?) + +=begin original + +The MIME-Base64 package (available from CPAN) handles this as well as +the MIME/QP encoding. Decoding BASE64 becomes as simple as: + +=end original + +MIME-Base64 パッケージ(CPAN で入手可能です)はこの問題と、 +MIME/QP エンコーディングを取り扱います。 +BASE64 のデコードは以下のように単純です: + + use MIME::Base64; + $decoded = decode_base64($encoded); + +=begin original + +The MIME-Tools package (available from CPAN) supports extraction with +decoding of BASE64 encoded attachments and content directly from email +messages. + +=end original + +MIME-Tools パッケージ (CPAN にあります) は BASE64 エンコードされた +添付ファイルと本文をメールのメッセージから直接抽出できます。 + +=begin original + +If the string to decode is short (less than 84 bytes long) +a more direct approach is to use the unpack() function's "u" +format after minor transliterations: + +=end original + +もしデコードしたい文字列が短い(84 文字以下)の場合、より直接的なやり方は、 +ちょっとした変換をした後で unpack() 関数の "u" フォーマットを +使うというものです: + + tr#A-Za-z0-9+/##cd; # remove non-base64 chars + tr#A-Za-z0-9+/# -_#; # convert to uuencoded format + $len = pack("c", 32 + 0.75*length); # compute length byte + print unpack("u", $len . $_); # uudecode and print + +=head2 How do I return the user's mail address? + +(ユーザーのメールアドレスを返すには?) + +=begin original + +On systems that support getpwuid, the $< variable, and the +Sys::Hostname module (which is part of the standard perl distribution), +you can probably try using something like this: + +=end original + +getpwuidをサポートしているシステムであれば、$< という変数と +Sys::Hostname モジュール(標準の perl 配布キットの一部です)を使って +以下のようなことが試せるでしょう。 + + use Sys::Hostname; + $address = sprintf('%s@%s', scalar getpwuid($<), hostname); + +=begin original + +Company policies on mail address can mean that this generates addresses +that the company's mail system will not accept, so you should ask for +users' mail addresses when this matters. Furthermore, not all systems +on which Perl runs are so forthcoming with this information as is Unix. + +=end original + +会社のメールアドレスに関するポリシーが、これが生成するアドレスは +その会社のメールシステムが受け付けないものである可能性があります。 +ですから、ユーザーに、そのユーザーのメールアドレスを尋ねるべきでしょう。 +それに加え、Perl が動作する全てのシステムで +この情報が(UNIX と同じように)得られるわけではありません。 + +=begin original + +The Mail::Util module from CPAN (part of the MailTools package) provides a +mailaddress() function that tries to guess the mail address of the user. +It makes a more intelligent guess than the code above, using information +given when the module was installed, but it could still be incorrect. +Again, the best way is often just to ask the user. + +=end original + +CPAN にある Mail::Util モジュール (MailTools パッケージの一部です)は +メールアドレスがそのユーザーのものであるかどうかを確かめようとする +mailaddress() という関数を提供しています。 +これは上で例示したやり方よりも賢く、モジュールがインストールされたときの +情報を使いますが、それでも正しくない可能性があります。 +くり返しますが、最善の方法はユーザーに尋ねること、というのがほとんどです。 + +=head2 How do I send mail? + +(メールを送るには?) + +=begin original + +Use the C<sendmail> program directly: + +=end original + +C<sendmail> プログラムを直接使います: + + open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq") + or die "Can't fork for sendmail: $!\n"; + print SENDMAIL <<"EOF"; + From: User Originating Mail <me\@host> + To: Final Destination <you\@otherhost> + Subject: A relevant subject line + + Body of the message goes here after the blank line + in as many lines as you like. + EOF + close(SENDMAIL) or warn "sendmail didn't close nicely"; + +=begin original + +The B<-oi> option prevents sendmail from interpreting a line consisting +of a single dot as "end of message". The B<-t> option says to use the +headers to decide who to send the message to, and B<-odq> says to put +the message into the queue. This last option means your message won't +be immediately delivered, so leave it out if you want immediate +delivery. + +=end original + +B<-oi> オプションは sendmail がドットだけの行を“メッセージの終わり”と +みなさないようにするためのオプションです。 +B<-t>オプションはメッセージを誰に贈るかを決めるかのために +ヘッダーを使うことを指示し、B<-odq> オプションメッセージを +キューに入れることを指示します。 +最後のオプションの意味は、あなたのメッセージがすぐには配送されないことを +意味します。 +ですから、すぐに配送させたいのであればこのオプションを取り除いてください。 + +=begin original + +Alternate, less convenient approaches include calling mail (sometimes +called mailx) directly or simply opening up port 25 have having an +intimate conversation between just you and the remote SMTP daemon, +probably sendmail. + +=end original + +あるいは、直接 mail (mailx と呼ばれることもあります)を +呼びだしたり、単純に 25 番ポートを使ってリモートの +SMTP デーモン(多分 sendmail でしょう) との間で +詳細な通信を行うといったあまり便利でない方法もあります。 + +=begin original + +Or you might be able use the CPAN module Mail::Mailer: + +=end original + +あるいは CPAN にあるモジュール Mail::Mailer が使えるかもしれません: + + use Mail::Mailer; + + $mailer = Mail::Mailer->new(); + $mailer->open({ From => $from_address, + To => $to_address, + Subject => $subject, + }) + or die "Can't open: $!\n"; + print $mailer $body; + $mailer->close(); + +=begin original + +The Mail::Internet module uses Net::SMTP which is less Unix-centric than +Mail::Mailer, but less reliable. Avoid raw SMTP commands. There +are many reasons to use a mail transport agent like sendmail. These +include queuing, MX records, and security. + +=end original + +Mail::Internet モジュールは Mail::Mailer より UNIX 的ではない +Net::SMTP を使っていますが、信頼性も低いです。 +生の SMTP コマンドを無視します。 +sendmail のような mail transport agent を使う理由はたくさんあります。 +その中にはキューイングも含まれますし、MX レコードやセキュリティと +いったものが含まれます。 + +=head2 How do I use MIME to make an attachment to a mail message? + +(メールメッセージに添付するためにどうやって MIME を使えばいいですか?) + +=begin original + +This answer is extracted directly from the MIME::Lite documentation. +Create a multipart message (i.e., one with attachments). + +=end original + +この回答は MIME::Lite のドキュメントから直接持ってきたものです。 +マルチパートメッセージ(つまり 添付つきのメッセージ) を作ります。 + + use MIME::Lite; + + ### Create a new multipart message: + $msg = MIME::Lite->new( + From =>'me****@myhos*****', + To =>'you****@yourh*****', + Cc =>'some****@other*****, some****@more*****', + Subject =>'A message with 2 parts...', + Type =>'multipart/mixed' + ); + + ### Add parts (each "attach" has same arguments as "new"): + $msg->attach(Type =>'TEXT', + Data =>"Here's the GIF file you wanted" + ); + $msg->attach(Type =>'image/gif', + Path =>'aaa000123.gif', + Filename =>'logo.gif' + ); + + $text = $msg->as_string; + +=begin original + +MIME::Lite also includes a method for sending these things. + +=end original + +MIME::Lite はまたこれらのものを送るためのメソッドを含みます。 + + $msg->send; + +=begin original + +This defaults to using L<sendmail> but can be customized to use +SMTP via L<Net::SMTP>. + +=end original + +これはデフォルトでは L<sendmail> を使いますが、 +L<Net::SMTP> 経由で SMTP を使うようにカスタマイズできます。 + +=head2 How do I read mail? + +(メールを読み出すには?) + +=begin original + +While you could use the Mail::Folder module from CPAN (part of the +MailFolder package) or the Mail::Internet module from CPAN (part +of the MailTools package), often a module is overkill. Here's a +mail sorter. + +=end original + +CPAN にある Mail::Folder モジュール(MailFolder パッケージの一部です)や +Mail::Internet モジュール(これも MailTools パッケージの一部です)が +使えますが、モジュールを使うのはやりすぎかもしれません。 +以下にメールをソートする方法を示します。 + + #!/usr/bin/perl + + my(@msgs, @sub); + my $msgno = -1; + $/ = ''; # paragraph reads + while (<>) { + if (/^From /m) { + /^Subject:\s*(?:Re:\s*)*(.*)/mi; + $sub[++$msgno] = lc($1) || ''; + } + $msgs[$msgno] .= $_; + } + for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) { + print $msgs[$i]; + } + +=begin original + +Or more succinctly, + +=end original + +あるいはもっと簡潔に: + + #!/usr/bin/perl -n00 + # bysub2 - awkish sort-by-subject + BEGIN { $msgno = -1 } + $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m; + $msg[$msgno] .= $_; + END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] } + +=head2 How do I find out my hostname, domainname, or IP address? +X<hostname, domainname, IP address, host, domain, hostfqdn, inet_ntoa, +gethostbyname, Socket, Net::Domain, Sys::Hostname> + +(私のホスト名/ドメイン名/IP アドレスを見つけるには?) + +=begin original + +(contributed by brian d foy) + +=end original + +(brian d foy によって寄贈されました) + +=begin original + +The Net::Domain module, which is part of the standard distribution starting +in perl5.7.3, can get you the fully qualified domain name (FQDN), the host +name, or the domain name. + +=end original + +perl5.7.3 から標準配布されている Net::Domain モジュールを使うと、 +完全修飾ドメイン名 (FQDN)、ホスト名、ドメイン名が得られます。 + + use Net::Domain qw(hostname hostfqdn hostdomain); + + my $host = hostfqdn(); + +=begin original + +The C<Sys::Hostname> module, included in the standard distribution since +perl5.6, can also get the hostname. + +=end original + +perl5.6 から標準配布されている C<Sys::Hostname> モジュールでも +ホスト名を得られます。 + + use Sys::Hostname; + + $host = hostname(); + +=begin original + +To get the IP address, you can use the C<gethostbyname> built-in function +to turn the name into a number. To turn that number into the dotted octet +form (a.b.c.d) that most people expect, use the C<inet_ntoa> function +from the <Socket> module, which also comes with perl. + +=end original + +IP アドレスを得るには、名前から数値に変換するために C<gethostbyname> +組み込み関数が使えます。 +数値を、ほとんどの人が想定しているピリオド付きの形 (a.b.c.d) に変換するには、 +標準配布されている C<Socket> モジュールの C<inet_ntoa> 関数を使います。 + + use Socket; + + my $address = inet_ntoa( + scalar gethostbyname( $host || 'localhost' ) + ); + +=head2 How do I fetch a news article or the active newsgroups? + +(ニュースの記事やアクティブなニュースグループを取得するには?) + +=begin original + +Use the Net::NNTP or News::NNTPClient modules, both available from CPAN. +This can make tasks like fetching the newsgroup list as simple as + +=end original + +Net::NNTP モジュールか News::NNTPClient モジュールのいずれかを使います。 +これらは両方ともCPANから入手可能です。 +これらは以下のように簡単にニュースグループのリストを取得するような +作業ができます。 + + perl -MNews::NNTPClient + -e 'print News::NNTPClient->new->list("newsgroups")' + +=head2 How do I fetch/put an FTP file? + +(FTP ファイルをダウンロード/アップロードするには?) + +=begin original + +LWP::Simple (available from CPAN) can fetch but not put. Net::FTP (also +available from CPAN) is more complex but can put as well as fetch. + +=end original + +LWP::Simple (CPAN で入手可能)はダウンロードができますが +アップロードはできません。 +Net::FTP(これも CPAN で入手可能)はこれよりも複雑ですが、 +ダウンロードとアップロードの両方ができます。 + +=head2 How can I do RPC in Perl? + +(Perl で RPC を行うには?) + +=begin original + +(Contributed by brian d foy) + +=end original + +(brian d foy によって寄贈されました) + +=begin original + +Use one of the RPC modules you can find on CPAN ( +http://search.cpan.org/search?query=RPC&mode=all ). + +=end original + +CPAN ( http://search.cpan.org/search?query=RPC&mode=all ) で見付かる +RFC モジュールの一つを使いましょう。 + +=head1 REVISION + +Revision: $Revision: 8539 $ + +Date: $Date: 2007-01-11 00:07:14 +0100 (Thu, 11 Jan 2007) $ + +See L<perlfaq> for source control details and availability. + +=head1 AUTHOR AND COPYRIGHT + +Copyright (c) 1997-2007 Tom Christiansen, Nathan Torkington, and +other authors as noted. All rights reserved. + +This documentation is free; you can redistribute it and/or modify it +under the same terms as Perl itself. + +Irrespective of its distribution, all code examples in this file +are hereby placed into the public domain. You are permitted and +encouraged to use this code in your own programs for fun +or for profit as you see fit. A simple comment in the code giving +credit would be courteous but is not required.