=encoding euc-jp =head1 NAME =begin original perlfaq9 - Networking =end original perlfaq9 - ネットワーク =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 answers...) =end original (Alan Flavell が答えます...) =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 These Perl FAQs very selectively cover some CGI issues. However, Perl programmers are strongly advised to use the C module, to take care of the details for them. =end original これらの Perl FAQ はいくつかの CGI の問題についてとても抜粋して カバーしています。 しかし、これらの詳細に用心するために、Perl プログラマは C モジュールを 使うことを強く忠告されます。 =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 (CGI 仕様に定義されている) CGI レスポンスヘッダと、(RFC2616 の HTTP 仕様で 定義されている) HTTP レスポンスヘッダの類似性は意図的なものですが、 時々混乱を引き起こします。 =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 CGI 仕様は 2 種類のスクリプトを定義しています: "Parsed Header" スクリプトと、"Non Parsed Header" (NPH) スクリプト。 何をサポートしているかについてはサーバーのドキュメントをチェックして ください。 "Parsed Header" スクリプトは色々な側面においてより単純です。 CGI 仕様は CGI レスポンスとして一般的な改行表現のどれを使ってもよいことに なっています(そこから正確な HTTP レスポンスを作成するのはサーバの仕事です)。 従って "\n" をテキストモードで書くのは技術的に正しく、推奨されています。 NPH スクリプトではより微妙です: ここでは完全に正確な HTTP トランザクション レスポンスヘッダを出力しなければなりません; HTTP 仕様はレコードが復帰と 改行(つまりバイナリモードで ASCII コードの \015\012 が書かれる)で 終端されていることを要求します。 =begin original Using C gives excellent platform independence, including EBCDIC systems. C selects an appropriate newline representation (C<$CGI::CRLF>) and sets binmode as appropriate. =end original C を使うことで、EBCDIC システムを含むすばらしいプラットフォーム 独立性が得られます。 C は適切な改行表現を選択し(C<$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 (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original There are many things that might be wrong with your CGI program, and only some of them might be related to Perl. Try going through the troubleshooting guide on Perlmonks: =end original CGI プログラムが悪いかもしれないいくつかのことがあり、その一部だけが Perl に関連します。 Perlmonks によるトラブルシューティングを確認してみてください: http://www.perlmonks.org/?node_id=380424 =head2 How can I get better error messages from a CGI program? (CGI プログラムから、もっとまともなエラーメッセージを得るには?) =begin original Use the C module. It replaces C and C, plus the normal C module's C, C, and C functions with more verbose and safer versions. It still sends them to the normal server error log. =end original C モジュールを使いましょう。 このモジュールは C と C の置き換えを行い、さらに通常の C モジュールの C、C、C といった関数をより饒舌で 安全なものに置き換えます。 その出力は、サーバーの通常のエラーログに送られます。 use CGI::Carp; warn "This is a complaint"; die "But this one is serious"; =begin original The following use of C also redirects errors to a file of your choice, placed in a C block to catch compile-time warnings as well: =end original 以下の C の使用例では、エラーをあなたの選択したファイルへ リダイレクトし、コンパイル時の警告も同様に補足するため C ブロックに 置いています: 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) with the application name and date stamp prepended. =end original あなたが HTTP ヘッダーを受け取るよりも前にエラーが起こったとしても、 モジュールはサーバーの 500 エラーを避けるためにそのエラーを取り扱おうと するでしょう。 通常の警告はサーバーのエラーログ(もしくはあなたが C で指定した場所)に アプリケーションの名前と日付を伴って送られます。 =head2 How do I remove HTML from a string? (ある文字列から HTML を取り除くには?) =begin original The most correct way (albeit not the fastest) is to use C from CPAN. Another mostly correct way is to use C which not only removes HTML but also attempts to do a little simple formatting of the resulting plain text. =end original (最速ではありませんが)最も正しい方法は、CPAN にある C を 使うというものです。 もう一つのまず正しい方法は、C を使って 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 comments 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/<(?:[^>'"]*|(['"]).*?\g1)*>//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 以下に挙げたのは、あなたが自分でやろうとしたときに 考慮すべきであろうトリッキーな例です: A > B A > B <# Just data #> >>>>>>>>>>> ]]> =begin original If HTML comments include other tags, those solutions would also break on text like this: =end original 以下のテキストのように HTML のコメントが他のタグを含んでいた場合には、 せっかくの対応策もダメにしてしまうかもしれません: =head2 How do I extract URLs? (URL の展開を行うには?) =begin original You can easily extract all sorts of URLs from HTML with C 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 or C. You might even use C as an example for something specifically suited to your needs. =end original アンカー、イメージ、オブジェクト、フレーム、およびその他の URL を含む 多くのタグを扱える C を使って、HTML からあらゆる 種類の URL を簡単に抽出できます。 もしもっと複雑なものが必要なら、自分自身で C や C のサブクラスを作れます。 例えば、あなたの用途に特に適用するなら、C を 使うこともできます。 =begin original You can use C to extract URLs from an arbitrary text document. =end original 任意のテキスト文書から URL を抽出するためには、C が使えます。 =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 もし入力が単純であることが分かっているなら、正規表現を使ったより不完全な 解法によって多くの処理時間を節約できます。 Tom Christiansen による一つの解法は、モジュールを使った手法よりも 100 倍 速いですが、最初の属性が HREF で、その他の属性がないアンカーの URL のみを 抽出します。 #!/usr/bin/perl -n00 # qxurl - tchrist@perl.com print "$2\n" while m{ < \s* A \s+ HREF \s* = \s* (["']) (.*?) \g1 \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 encoding. The C module (which comes with Perl as part of the Standard Library) supports this in the C method, which isn't the same as the C method. =end original この場合、ダウンロードというのは HTML フォームのファイルアップロード機能を 使うということを意味します。 Web サーファーに、Web サーバーに送るファイルを指定できるようにします。 あなたにとってダウンロードに見えるものは、ユーザーにとってはアップロードに 見えます。 何と呼ぶかには関わらず、B エンコーディングとして知られているものを使うことができるでしょう。 C モジュール(標準ライブラリになっています)はこれを C という C メソッドとは異なるメソッドでサポートしています。 =begin original See the section in the C documentation on file uploads for code examples and details. =end original コードのサンプルと詳細については、C の文書のファイルアップロードの 章を参照してください。 =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 C module (which comes with Perl) has functions to create the HTML form widgets. See the C documentation for more examples. =end original C モジュール(標準配布です)には HTML フォームウィジェットを作るための 関数があります。 更なる例については C の文書を参照してください。 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 (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original Use the libwww-perl distribution. The C module can fetch web resources and give their content back to you as a string: =end original libwww-perl ディストリビューションを使ってください。 C はウェブ上のリソースをフェッチして、その内容を文字列として 返します: use LWP::Simple qw(get); my $html = get( "http://www.example.com/index.html" ); =begin original It can also store the resource directly in a file: =end original リソースを直接ファイルに保存することもできます: use LWP::Simple qw(getstore); getstore( "http://www.example.com/index.html", "foo.html" ); =begin original If you need to do something more complicated, you can use C module to create your own user-agent (e.g. browser) to get the job done. If you want to simulate an interactive web browser, you can use the C module. =end original もっと複雑なことをする必要がある場合は、仕事を行うための独自の ユーザーエージェント(例えばブラウザ)を作るために C モジュールを使えます。 対話的なウェブブラウザをシミュレートしたい場合は、 C モジュールが使えます。 =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. See its documentation for all the details. =end original もし、複数のページとフォームや web サイトを移動するような、複雑なことを しようとしているなら、C が使えます。 全ての詳細についてはこれのドキュメントを参照してください。 =begin original If you're submitting values using the GET method, create a URL and encode the form using the C method: =end original GET メソッドを使って値を処理しているのであれば、URL を作って、 さらに C メソッドを使ってフォームをエンコードします: 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? X X X X X (web上で %-encodings をデコードしたり生成したりするには?) =begin original (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original Those C<%> encodings handle reserved characters in URIs, as described in RFC 2396, Section 2. This encoding replaces the reserved character with the hexadecimal representation of the character's number from the US-ASCII table. For instance, a colon, C<:>, becomes C<%3A>. =end original これらの C<%> 符号化は RFC 2396 の 2 章に記述されている、 URI として予約されている文字を扱います。 この符号化は予約文字を、その文字の番号の 16 進表現に US-ASCII テーブルを使って置き換えます。 例えば、コロン (C<:>) は C<%3A> になります。 =begin original In CGI scripts, you don't have to worry about decoding URIs if you are using C. You shouldn't have to process the URI yourself, either on the way in or the way out. =end original CGI スクリプトでは、C を使っているなら URL のデコードについて 気にする必要はありません。 エンコードにしてもデコードにしても、URI を自分で処理する必要はないはずです。 =begin original If you have to encode a string yourself, remember that you should never try to encode an already-composed URI. You need to escape the components separately then put them together. To encode a string, you can use the C module. The C function returns the escaped string: =end original もし文字列を自分でエンコードする必要があるなら、 決してすでに構成された URI をエンコードするべきではないことを 忘れないでください。 要素を別々にエスケープして、それから全てを合わせます。 文字列をエンコードするには、C モジュールが使えます。 C 関数はエスケープされた文字列を返します: my $original = "Colon : Hash # Percent %"; my $escaped = uri_escape( $original ); print "$escaped\n"; # 'Colon%20%3A%20Hash%20%23%20Percent%20%25' =begin original To decode the string, use the C function: =end original 文字列をデコードするには、C 関数を使います: my $unescaped = uri_unescape( $escaped ); print $unescaped; # back to original =begin original If you wanted to do it yourself, you simply need to replace the reserved characters with their encodings. A global substitution is one way to do it: =end original もしこれを自分でするなら、単に予約文字をエンコードされた物に置き換えます。 全体を一度に変換するなら、以下のようにします: # encode $string =~ s/([^^A-Za-z0-9\-_.!~*'()])/ sprintf "%%%0x", ord $1 /eg; #decode $string =~ s/%([A-Fa-f\d]{2})/chr hex $1/eg; =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 (たとえ同じサーバでも)宛て先の完全な URL を指定してください。 これは Parsed Headers スクリプトとして CGI 仕様に定義された二つの異なった CGI "Location:" レスポンスのうちの一つです。 その他の種類 (絶対 URL パス) は HTTP リダイレクトなしにサーバによって 内部的に解決されます。 CGI 仕様ではどちらの場合でも相対 URL は認められていません。 =begin original Use of C is strongly recommended. This example shows redirection with a complete URL. This redirection is handled by the web browser. =end original C を使うことを強くお勧めします。 この例では完全な 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 しかし、直接コーディングするなら、完全な URL か絶対 URLpath を使って、 以下のようになります(最後の "\n" は明確化するために分けて表示しています)。 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 利用する Web サーバーで認証を有効にするには、Web サーバーを設定することが 必要です。 web サーバの種類によって設定は異なります -- apache は iPlanet とは異なり、 また IIS とも異なります。 特定のサーバーに関する詳細については、そのサーバーのドキュメントを チェックしてください。 =head2 How do I edit my .htpasswd and .htgroup files with Perl? (Perl を使って .htpasswd や .htgroup といったファイルを編集するには?) =begin original The C and C 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. C supports files used by the "Basic" and "Digest" authentication schemes. Here's an example: =end original C モジュールと C モジュールは、 ファイルがどのように格納されているかに関係なくこれらのファイルに対する 首尾一貫したオブジェクト指向インターフェースを提供します。 データベースはテキスト、dbm、Berkeley DB、あるいは DBI 互換ドライバのある どんなデータベースでもかまいません。 C は "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 (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original You can't prevent people from sending your script bad data. Even if you add some client-side checks, people may disable them or bypass them completely. For instance, someone might use a module such as C to access your CGI program. If you want to prevent data that try to use SQL injection or other sorts of attacks (and you should want to), you have to not trust any data that enter your program. =end original 人々がスクリプトに悪いデータを送るのを防ぐことは出来ません。 例えクライアント側でチェックをしたとしても、それを無効にしたり 完全に回避したりできます。 例えば、CGI プログラムに C のようなモジュールを使うかもしれません。 SQL インジェクションや同様の種類の攻撃を行うようなデータを防ぎたいのなら (そしておそらくそうしたいでしょう)、プログラムに入力される どんなデータも信用しないようにする必要があります。 =begin original The L documentation has general advice about data security. If you are using the C module, use placeholder to fill in data. If you are running external programs with C or C, use the list forms. There are many other precautions that you should take, too many to list here, and most of them fall under the category of not using any data that you don't intend to use. Trust no one. =end original L 文書にはデータセキュリティに関する一般的な助言があります。 C モジュールを使っているなら、データを埋めるのにプレースホルダを 使ってください。 C や C で外部プログラムを実行しているなら、リスト形式を 使ってください。 その他、ここに書ききれないほどの注意するべき多くの事前注意があり、 そのほとんどは、使おうとしていないデータは使わないという分野に当てはまります。 誰も信用しないでください。 =head2 How do I parse a mail header? (メールのヘッダーを解析するには?) =begin original For a quick-and-dirty solution, try this solution derived from L: =end original 拙速な解決策なら、L から派生した 以下のやり方を試してみてください: $/ = ''; $header = ; $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 C module from CPAN (part of the C package). =end original このやり方は、たとえば受信した行すべてを保守しようとするときには うまくありません。 より完璧なアプローチは CPAN にある C モジュールを 使うというものです(このモジュールは C パッケージの一部です)。 =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 C 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 に同梱されている C モジュールを使いましょう。 これは早く、簡単で、物事が正しく行われることを確実にするための ちょっとした作業を行います。 GET, POST, HEAD リクエスト、マルチパートフォーム、複数値フィールド、 クエリ文字列とメッセージボディの組み合わせ、およびその他の、 あなたが考えようとも思わないような多くの事柄を扱えます。 =begin original It doesn't get much easier: the C module automatically parses the input and makes each value available through the C function. =end original これ以上簡単にはなりません: C モジュールは入力を自動的にパースして、 それぞれの値を C 関数を通して利用可能にします。 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, C can do that too. =end original オブジェクト指向な手法が使いたいなら、C はそのようにもできます。 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 C which is a lightweight version of the same thing. Other CGI::* modules on CPAN might work better for you, too. =end original 同じことをする軽量版の C も試したいかもしれません。 CPAN にあるその他の CGI::* モジュールもあなたのためによく働くでしょう。 =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 C. =end original 多くの人々が自分用のデコーダを書こうとします (あるいは他のプログラムから コピーしようとします); そしてこの作業の多くの「コツ」の一つに出くわすことに なります。 C を使うことはより簡単で、面倒事も少なくなります。 =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, but either the C or the C module will do both part I and part I as far as you can in real-time. =end original そのアドレスにメールを送ってそれが届いたかどうかを確認しなければ 完全にパート I に答えられませんが、C か C のモジュールは、リアルタイムでできる限りの ことに対してパート I とパート I の両方を行います。 =begin original If you want to just check part I 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 matches the address itself: =end original もしあなたが単純な正規表現でアドレスがメールヘッダ標準に従っているかを 見ることでパート I をチェックしたいなら、問題を抱えることになります; なぜなら、RFC-2822 (最新のメールヘッダ標準) に準拠してないけれども 配達可能なアドレスが存在し、標準に準拠しているけれども配達不能なアドレスも 存在するからです。 しかし以下のコードは、コメント、折り畳みの空白、あるいはその他の時代遅れに なっていたり本質的でない要素を含んでいない、有効な RFC-2822 アドレスに マッチングします。 これは I<単に> アドレス自身にマッチングします: 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 $quotedpair = qr{\\[\x00-\x09\x0B-\x0c\x0e-\x7e]}; my $domain_lit = qr{\[(?:$quotedpair|[\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 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 もしアドレスが RFC 2822 仕様に準拠しているかどうかを見たいなら、単に C とマッチングさせてください。 しかし、このような正しい形式のアドレスが実際に特定の個人に届く 正しい方法なのか、あるいはその個人に関連付けられたメールボックスに 届くのかさえも明確にすることは不可能なので、これをどう使うかについては とても慎重になる必要があります。 =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 C package (available from CPAN) handles this as well as the MIME/QP encoding. Decoding BASE64 becomes as simple as: =end original C パッケージ(CPAN で入手可能です)はこの問題と、 MIME/QP エンコーディングを取り扱います。 BASE64 のデコードは以下のように単純です: use MIME::Base64; $decoded = decode_base64($encoded); =begin original The C package (available from CPAN) supports extraction with decoding of BASE64 encoded attachments and content directly from email messages. =end original C パッケージ (CPAN にあります) は BASE64 エンコードされた 添付ファイルと本文をメールのメッセージから直接抽出できます。 =begin original If the string to decode is short (less than 84 bytes long) a more direct approach is to use the C function's "u" format after minor transliterations: =end original もしデコードしたい文字列が短い(84 文字以下)の場合、より直接的なやり方は、 ちょっとした変換をした後で C 関数の "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 C<< $< >> variable, and the C module (which is part of the standard perl distribution), you can probably try using something like this: =end original getpwuid をサポートしているシステムであれば、C<< $< >> という変数と C モジュール(標準の 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 C module from CPAN (part of the C package) provides a C 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 にある C モジュール (C パッケージの一部です)は メールアドレスがそのユーザーのものであるかどうかを確かめようとする C という関数を提供しています。 これは上で例示したやり方よりも賢く、モジュールがインストールされたときの 情報を使いますが、それでも正しくない可能性があります。 くり返しますが、最善の方法はユーザーに尋ねること、というのがほとんどです。 =head2 How do I send mail? (メールを送るには?) =begin original Use the C program directly: =end original C プログラムを直接使います: open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq") or die "Can't fork for sendmail: $!\n"; print SENDMAIL <<"EOF"; From: User Originating Mail To: Final Destination 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 C 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> オプションは C がドットだけの行を“メッセージの終わり”と みなさないようにするためのオプションです。 B<-t>オプションはメッセージを誰に送るかを決めるかのために ヘッダーを使うことを指示し、B<-odq> オプションメッセージを キューに入れることを指示します。 最後のオプションの意味は、あなたのメッセージがすぐには配送されないことを 意味します。 ですから、すぐに配送させたいのであればこのオプションを取り除いてください。 =begin original Alternate, less convenient approaches include calling C (sometimes called C) directly or simply opening up port 25 have having an intimate conversation between just you and the remote SMTP daemon, probably C. =end original あるいは、直接 C (C と呼ばれることもあります)を呼びだしたり、 単純に 25 番ポートを使ってリモートの SMTP デーモン(多分 C でしょう) との間で詳細な通信を行うといったあまり便利でない方法もあります。 =begin original Or you might be able use the CPAN module C: =end original あるいは CPAN にあるモジュール C が使えるかもしれません: 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 C module uses C which is less Unix-centric than C, but less reliable. Avoid raw SMTP commands. There are many reasons to use a mail transport agent like C. These include queuing, MX records, and security. =end original C モジュールは C より UNIX 的ではない C を使っていますが、信頼性も低いです。 生の SMTP コマンドを無視します。 C のような 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 C documentation. Create a multipart message (i.e., one with attachments). =end original この回答は C のドキュメントから直接持ってきたものです。 マルチパートメッセージ(つまり 添付つきのメッセージ) を作ります。 use MIME::Lite; ### Create a new multipart message: $msg = MIME::Lite->new( From =>'me@myhost.com', To =>'you@yourhost.com', Cc =>'some@other.com, some@more.com', 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 C also includes a method for sending these things. =end original C はまたこれらのものを送るためのメソッドを含みます。 $msg->send; =begin original This defaults to using L but can be customized to use SMTP via L. =end original これはデフォルトでは L を使いますが、 L 経由で SMTP を使うようにカスタマイズできます。 =head2 How do I read mail? (メールを読み出すには?) =begin original While you could use the C module from CPAN (part of the C package) or the C module from CPAN (part of the C package), often a module is overkill. Here's a mail sorter. =end original CPAN にある C モジュール(C パッケージの一部です)や C モジュール(これも C パッケージの一部です)が 使えますが、モジュールを使うのはやりすぎかもしれません。 以下にメールをソートする方法を示します。 #!/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 (私のホスト名/ドメイン名/IP アドレスを見つけるには?) =begin original (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original The C 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 から標準配布されている C モジュールを使うと、 完全修飾ドメイン名 (FQDN)、ホスト名、ドメイン名が得られます。 use Net::Domain qw(hostname hostfqdn hostdomain); my $host = hostfqdn(); =begin original The C module, included in the standard distribution since perl5.6, can also get the hostname. =end original perl5.6 から標準配布されている C モジュールでも ホスト名を得られます。 use Sys::Hostname; $host = hostname(); =begin original To get the IP address, you can use the C 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 function from the C module, which also comes with perl. =end original IP アドレスを得るには、名前から数値に変換するために C 組み込み関数が使えます。 数値を、ほとんどの人が想定しているピリオド付きの形 (a.b.c.d) に変換するには、 標準配布されている C モジュールの C 関数を使います。 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 C or C modules, both available from CPAN. This can make tasks like fetching the newsgroup list as simple as =end original C モジュールか C モジュールのいずれかを使います。 これらは両方とも CPAN から入手可能です。 これらは以下のように簡単にニュースグループのリストを取得するような 作業ができます。 perl -MNews::NNTPClient -e 'print News::NNTPClient->new->list("newsgroups")' =head2 How do I fetch/put an FTP file? (FTP ファイルをダウンロード/アップロードするには?) =begin original (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original The C family of modules (available on CPAN as the libwww-perl distribution) can work with FTP just like it can with many other protocols. C makes it quite easy to fetch a file: =end original C モジュールファミリー (CPAN で libwww-perl 配布として利用可能です) は FTP をその他のプロトコルと同様に扱えます。 C はファイルをダウンロードするのをとても簡単にします: use LWP::Simple; my $data = get( 'ftp://some.ftp.site/some/file.txt' ); =begin original If you want more direct or low-level control of the FTP process, you can use the C module (in the Standard Library since Perl 5.8). It's documentation has examples showing you just how to do that. =end original FTP 処理をより直接的に、あるいは低レベルの制御がしたいなら、(Perl 5.8 以降 標準ライブラリに入っている) C モジュールが使えます。 その文書にはこれを行う方法を示すための例が載っています。 =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 AUTHOR AND COPYRIGHT Copyright (c) 1997-2010 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. =begin meta Translate: 吉村 寿人 Update: SHIRAKATA Kentaro (5.6.1-) Status: completed =end meta