5.14.1

名前

perlfaq9 - Networking

perlfaq9 - ネットワーク

説明

This section deals with questions related to networking, the internet, and a few on the web.

このセクションでは、ネットワーク、インターネット、web に関する 質問を扱っています。

CGI スクリプトからの返答の正しい形は?

(Alan Flavell <flavell+www@a5.ph.gla.ac.uk> answers...)

(Alan Flavell <flavell+www@a5.ph.gla.ac.uk> が答えます...)

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

The Common Gateway Interface (CGI) はプログラム("CGI スクリプト")と web サーバ (HTTPD) の間のソフトウェアインターフェースを定めています。 これは Perl 固有のものではないので、独自の FAQと独自のチュートリアル、 そして独自の usenet group である comp.infosystems.www.authoring.cgi が あります。

The CGI specification is outlined in an informational RFC: http://www.ietf.org/rfc/rfc3875

CGI 仕様は RFC に概要が述べられています: http://www.ietf.org/rfc/rfc3875

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.

これらの Perl FAQ はいくつかの CGI の問題についてとても抜粋して カバーしています。 しかし、これらの詳細に用心するために、Perl プログラマは CGI モジュールを 使うことを強く忠告されます。

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.

(CGI 仕様に定義されている) CGI レスポンスヘッダと、(RFC2616 の HTTP 仕様で 定義されている) HTTP レスポンスヘッダの類似性は意図的なものですが、 時々混乱を引き起こします。

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.

CGI 仕様は 2 種類のスクリプトを定義しています: "Parsed Header" スクリプトと、"Non Parsed Header" (NPH) スクリプト。 何をサポートしているかについてはサーバーのドキュメントをチェックして ください。 "Parsed Header" スクリプトは色々な側面においてより単純です。 CGI 仕様は CGI レスポンスとして一般的な改行表現のどれを使ってもよいことに なっています(そこから正確な HTTP レスポンスを作成するのはサーバの仕事です)。 従って "\n" をテキストモードで書くのは技術的に正しく、推奨されています。 NPH スクリプトではより微妙です: ここでは完全に正確な HTTP トランザクション レスポンスヘッダを出力しなければなりません; HTTP 仕様はレコードが復帰と 改行(つまりバイナリモードで ASCII コードの \015\012 が書かれる)で 終端されていることを要求します。

Using CGI.pm gives excellent platform independence, including EBCDIC systems. CGI.pm selects an appropriate newline representation ($CGI::CRLF) and sets binmode as appropriate.

CGI.pm を使うことで、EBCDIC システムを含むすばらしいプラットフォーム 独立性が得られます。 CGI.pm は適切な改行表現を選択し($CGI::CRLF)、binmode を適切にセットします。

私の CGI スクリプトはコマンドラインでは動くのだけど、ブラウザ上では動きません (500 Server Error になります)

(contributed by brian d foy)

(brian d foy によって寄贈されました)

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:

CGI プログラムが悪いかもしれないいくつかのことがあり、その一部だけが Perl に関連します。 Perlmonks によるトラブルシューティングを確認してみてください:

        http://www.perlmonks.org/?node_id=380424

CGI プログラムから、もっとまともなエラーメッセージを得るには?

Use the CGI::Carp module. It replaces warn and die, plus the normal Carp module's carp, croak, and confess functions with more verbose and safer versions. It still sends them to the normal server error log.

CGI::Carp モジュールを使いましょう。 このモジュールは warndie の置き換えを行い、さらに通常の Carp モジュールの carpcroakconfess といった関数をより饒舌で 安全なものに置き換えます。 その出力は、サーバーの通常のエラーログに送られます。

        use CGI::Carp;
        warn "This is a complaint";
        die "But this one is serious";

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:

以下の 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);
        }

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.

深刻なエラーをクライアントのブラウザに戻すように変更することもできます。 これはあなたがデバッグするには良いでしょうが、エンドユーザーを 混乱させてしまうかもしれません。

        use CGI::Carp qw(fatalsToBrowser);
        die "Bad error here";

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 carpout) with the application name and date stamp prepended.

あなたが HTTP ヘッダーを受け取るよりも前にエラーが起こったとしても、 モジュールはサーバーの 500 エラーを避けるためにそのエラーを取り扱おうと するでしょう。 通常の警告はサーバーのエラーログ(もしくはあなたが carpout で指定した場所)に アプリケーションの名前と日付を伴って送られます。

ある文字列から HTML を取り除くには?

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.

(最速ではありませんが)最も正しい方法は、CPAN にある HTML::Parser を 使うというものです。 もう一つのまず正しい方法は、HTML::FormatText を使って HTML を 取り除くだけでなく、結果のプレーンテキストを簡単に整形することです。

Many folks attempt a simple-minded regular expression approach, like 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 &lt; for example.

多くの人が、s/<.*?>//g のような単純な(simple-minded)正規表現を 使ったアプローチを行おうとするのですが、これは多くの場合 失敗していまいます。 なぜなら、タグは行をまたがって継続する可能性があり、 クォートされたアングルブラケットを含む可能性があり、 HTML のコメントがあるかもしれないからです。 さらに、人々は &lt; のようなエンティティを変換することを忘れてしまうのです。

Here's one "simple-minded" approach, that works for most files:

以下の例は「単純な」アプローチで、ほとんどのファイルに対しては うまくいきます:

        #!/usr/bin/perl -p0777
        s/<(?:[^>'"]*|(['"]).*?\g1)*>//gs

If you want a more complete solution, see the 3-stage striphtml program in http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz .

もし、より完璧な解決策を求めているのなら、 http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz にある 3-stage striphtml プログラムを参照してみてください。

Here are some tricky cases that you should think about when picking a solution:

以下に挙げたのは、あなたが自分でやろうとしたときに 考慮すべきであろうトリッキーな例です:

        <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 [ >>>>>>>>>>>> ]]>

If HTML comments include other tags, those solutions would also break on text like this:

以下のテキストのように HTML のコメントが他のタグを含んでいた場合には、 せっかくの対応策もダメにしてしまうかもしれません:

        <!-- This section commented out.
                <B>You can't see me!</B>
        -->

URL の展開を行うには?

You can easily extract all sorts of URLs from HTML with 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 HTML::LinkExtor or HTML::Parser. You might even use HTML::SimpleLinkExtor as an example for something specifically suited to your needs.

アンカー、イメージ、オブジェクト、フレーム、およびその他の URL を含む 多くのタグを扱える HTML::SimpleLinkExtor を使って、HTML からあらゆる 種類の URL を簡単に抽出できます。 もしもっと複雑なものが必要なら、自分自身で HTML::LinkExtorHTML::Parser のサブクラスを作れます。 例えば、あなたの用途に特に適用するなら、HTML::SimpleLinkExtor を 使うこともできます。

You can use URI::Find to extract URLs from an arbitrary text document.

任意のテキスト文書から URL を抽出するためには、URI::Find が使えます。

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.

もし入力が単純であることが分かっているなら、正規表現を使ったより不完全な 解法によって多くの処理時間を節約できます。 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;

ユーザーのマシンからファイルをダウンロードするには? 別のマシンにあるファイルをオープンするには?

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 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.

この場合、ダウンロードというのは HTML フォームのファイルアップロード機能を 使うということを意味します。 Web サーファーに、Web サーバーに送るファイルを指定できるようにします。 あなたにとってダウンロードに見えるものは、ユーザーにとってはアップロードに 見えます。 何と呼ぶかには関わらず、multipart/form-data エンコーディングとして知られているものを使うことができるでしょう。 CGI.pm モジュール(標準ライブラリになっています)はこれを start_multipart_form() という starform() メソッドとは異なるメソッドでサポートしています。

See the section in the CGI.pm documentation on file uploads for code examples and details.

コードのサンプルと詳細については、CGI.pm の文書のファイルアップロードの 章を参照してください。

Perl で HTML のポップアップメニューを作るには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

The CGI.pm module (which comes with Perl) has functions to create the HTML form widgets. See the CGI.pm documentation for more examples.

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;

HTML ファイルをフェッチするには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

Use the libwww-perl distribution. The LWP::Simple module can fetch web resources and give their content back to you as a string:

libwww-perl ディストリビューションを使ってください。 LWP::Simple はウェブ上のリソースをフェッチして、その内容を文字列として 返します:

        use LWP::Simple qw(get);

        my $html = get( "http://www.example.com/index.html" );

It can also store the resource directly in a file:

リソースを直接ファイルに保存することもできます:

        use LWP::Simple qw(getstore);

        getstore( "http://www.example.com/index.html", "foo.html" );

If you need to do something more complicated, you can use LWP::UserAgent 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 WWW::Mechanize module.

もっと複雑なことをする必要がある場合は、仕事を行うための独自の ユーザーエージェント(例えばブラウザ)を作るために LWP::UserAgent モジュールを使えます。 対話的なウェブブラウザをシミュレートしたい場合は、 WWW::Mechanize モジュールが使えます。

HTML フォームの処理を自動化するには?

If you are doing something complex, such as moving through many pages and forms or a web site, you can use WWW::Mechanize. See its documentation for all the details.

もし、複数のページとフォームや web サイトを移動するような、複雑なことを しようとしているなら、WWW::Mechanize が使えます。 全ての詳細についてはこれのドキュメントを参照してください。

If you're submitting values using the GET method, create a URL and encode the form using the query_form method:

GET メソッドを使って値を処理しているのであれば、URL を作って、 さらに 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);

If you're using the POST method, create your own user agent and encode the content appropriately.

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;

web上で %-encodings をデコードしたり生成したりするには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

Those % 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, :, becomes %3A.

これらの % 符号化は RFC 2396 の 2 章に記述されている、 URI として予約されている文字を扱います。 この符号化は予約文字を、その文字の番号の 16 進表現に US-ASCII テーブルを使って置き換えます。 例えば、コロン (:) は %3A になります。

In CGI scripts, you don't have to worry about decoding URIs if you are using CGI.pm. You shouldn't have to process the URI yourself, either on the way in or the way out.

CGI スクリプトでは、CGI.pm を使っているなら URL のデコードについて 気にする必要はありません。 エンコードにしてもデコードにしても、URI を自分で処理する必要はないはずです。

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 URI::Escape module. The uri_escape function returns the escaped string:

もし文字列を自分でエンコードする必要があるなら、 決してすでに構成された URI をエンコードするべきではないことを 忘れないでください。 要素を別々にエスケープして、それから全てを合わせます。 文字列をエンコードするには、URI::Escape モジュールが使えます。 uri_escape 関数はエスケープされた文字列を返します:

        my $original = "Colon : Hash # Percent %";

        my $escaped = uri_escape( $original );

        print "$escaped\n"; # 'Colon%20%3A%20Hash%20%23%20Percent%20%25'

To decode the string, use the uri_unescape function:

文字列をデコードするには、uri_unescape 関数を使います:

        my $unescaped = uri_unescape( $escaped );

        print $unescaped; # back to 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:

もしこれを自分でするなら、単に予約文字をエンコードされた物に置き換えます。 全体を一度に変換するなら、以下のようにします:

        # encode
        $string =~ s/([^^A-Za-z0-9\-_.!~*'()])/ sprintf "%%%0x", ord $1 /eg;

        #decode
        $string =~ s/%([A-Fa-f\d]{2})/chr hex $1/eg;

別のページにリダイレクトするには?

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.

(たとえ同じサーバでも)宛て先の完全な URL を指定してください。 これは Parsed Headers スクリプトとして CGI 仕様に定義された二つの異なった CGI "Location:" レスポンスのうちの一つです。 その他の種類 (絶対 URL パス) は HTTP リダイレクトなしにサーバによって 内部的に解決されます。 CGI 仕様ではどちらの場合でも相対 URL は認められていません。

Use of CGI.pm is strongly recommended. This example shows redirection with a complete URL. This redirection is handled by the web browser.

CGI.pm を使うことを強くお勧めします。 この例では完全な URL へのリダイレクトを行います。 このリダイレクトは web ブラウザによって扱われます。

        use CGI qw/:standard/;

        my $url = 'http://www.cpan.org/';
        print redirect($url);

This example shows a redirection with an absolute URLpath. This redirection is handled by the local web server.

この例では絶対 URL パスへのリダイレクトを行います。 このリダイレクトはローカルの web サーバによって行われます。

        my $url = '/CPAN/index.html';
        print redirect($url);

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.

しかし、直接コーディングするなら、完全な URL か絶対 URLpath を使って、 以下のようになります(最後の "\n" は明確化するために分けて表示しています)。

        print "Location: $url\n";   # CGI response header
        print "\n";                 # end of headers

私の web ぺージでパスワードを入力するには?

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.

利用する Web サーバーで認証を有効にするには、Web サーバーを設定することが 必要です。 web サーバの種類によって設定は異なります -- apache は iPlanet とは異なり、 また IIS とも異なります。 特定のサーバーに関する詳細については、そのサーバーのドキュメントを チェックしてください。

Perl を使って .htpasswd や .htgroup といったファイルを編集するには?

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:

HTTPD::UserAdmin モジュールと HTTPD::GroupAdmin モジュールは、 ファイルがどのように格納されているかに関係なくこれらのファイルに対する 首尾一貫したオブジェクト指向インターフェースを提供します。 データベースはテキスト、dbm、Berkeley DB、あるいは DBI 互換ドライバのある どんなデータベースでもかまいません。 HTTPD::UserAdmin は "Basic" および "Digest" 認証スキームで 使われるファイルをサポートします。 以下に例を挙げます:

        use HTTPD::UserAdmin ();
        HTTPD::UserAdmin
          ->new(DB => "/foo/.htpasswd")
          ->add($username => $password);

私の CGI スクリプトに悪影響をもたらすようなものを、ユーザーがフォームに入力できないようにするには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

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 LWP 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.

人々がスクリプトに悪いデータを送るのを防ぐことは出来ません。 例えクライアント側でチェックをしたとしても、それを無効にしたり 完全に回避したりできます。 例えば、CGI プログラムに LWP のようなモジュールを使うかもしれません。 SQL インジェクションや同様の種類の攻撃を行うようなデータを防ぎたいのなら (そしておそらくそうしたいでしょう)、プログラムに入力される どんなデータも信用しないようにする必要があります。

The perlsec documentation has general advice about data security. If you are using the DBI module, use placeholder to fill in data. If you are running external programs with system or exec, 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.

perlsec 文書にはデータセキュリティに関する一般的な助言があります。 DBI モジュールを使っているなら、データを埋めるのにプレースホルダを 使ってください。 systemexec で外部プログラムを実行しているなら、リスト形式を 使ってください。 その他、ここに書ききれないほどの注意するべき多くの事前注意があり、 そのほとんどは、使おうとしていないデータは使わないという分野に当てはまります。 誰も信用しないでください。

メールのヘッダーを解析するには?

For a quick-and-dirty solution, try this solution derived from "split" in perlfunc:

拙速な解決策なら、"split" in perlfunc から派生した 以下のやり方を試してみてください:

        $/ = '';
        $header = <MSG>;
        $header =~ s/\n\s+/ /g;  # merge continuation lines
        %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );

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).

このやり方は、たとえば受信した行すべてを保守しようとするときには うまくありません。 より完璧なアプローチは CPAN にある Mail::Header モジュールを 使うというものです(このモジュールは MailTools パッケージの一部です)。

CGI フォームをデコードするには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

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.

Perl に同梱されている CGI.pm モジュールを使いましょう。 これは早く、簡単で、物事が正しく行われることを確実にするための ちょっとした作業を行います。 GET, POST, HEAD リクエスト、マルチパートフォーム、複数値フィールド、 クエリ文字列とメッセージボディの組み合わせ、およびその他の、 あなたが考えようとも思わないような多くの事柄を扱えます。

It doesn't get much easier: the CGI.pm module automatically parses the input and makes each value available through the param() function.

これ以上簡単にはなりません: CGI.pm モジュールは入力を自動的にパースして、 それぞれの値を param() 関数を通して利用可能にします。

        use CGI qw(:standard);

        my $total = param( 'price' ) + param( 'shipping' );

        my @items = param( 'item' ); # multiple values, same field name

If you want an object-oriented approach, CGI.pm can do that too.

オブジェクト指向な手法が使いたいなら、CGI.pm はそのようにもできます。

        use CGI;

        my $cgi = CGI->new();

        my $total = $cgi->param( 'price' ) + $cgi->param( 'shipping' );

        my @items = $cgi->param( 'item' );

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.

同じことをする軽量版の CGI::Minimal も試したいかもしれません。 CPAN にあるその他の CGI::* モジュールもあなたのためによく働くでしょう。

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.

多くの人々が自分用のデコーダを書こうとします (あるいは他のプログラムから コピーしようとします); そしてこの作業の多くの「コツ」の一つに出くわすことに なります。 CGI.pm を使うことはより簡単で、面倒事も少なくなります。

メールアドレスが正しいかチェックするには?

(partly contributed by Aaron Sherman)

(一部は Aaron Sherman によって寄贈されました)

This isn't as simple a question as it sounds. There are two parts:

これは見た目ほど単純な質問ではありません。 これは二つの部分からなります:

a) How do I verify that an email address is correctly formatted?

a) メールアドレスが正しい形式かを検証するには?

b) How do I verify that an email address targets a valid recipient?

b) メールアドレスが正当な受信者を対象としているかを検証するには?

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 b, but either the Email::Valid or the RFC::RFC822::Address module will do both part a and part b as far as you can in real-time.

そのアドレスにメールを送ってそれが届いたかどうかを確認しなければ 完全にパート b に答えられませんが、Email::ValidRFC::RFC822::Address のモジュールは、リアルタイムでできる限りの ことに対してパート a とパート b の両方を行います。

If you want to just check part 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 just matches the address itself:

もしあなたが単純な正規表現でアドレスがメールヘッダ標準に従っているかを 見ることでパート a をチェックしたいなら、問題を抱えることになります; なぜなら、RFC-2822 (最新のメールヘッダ標準) に準拠してないけれども 配達可能なアドレスが存在し、標準に準拠しているけれども配達不能なアドレスも 存在するからです。 しかし以下のコードは、コメント、折り畳みの空白、あるいはその他の時代遅れに なっていたり本質的でない要素を含んでいない、有効な RFC-2822 アドレスに マッチングします。 これは 単に アドレス自身にマッチングします:

        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};

Just match an address against /^${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.

もしアドレスが RFC 2822 仕様に準拠しているかどうかを見たいなら、単に /^${addr_spec}$/ とマッチングさせてください。 しかし、このような正しい形式のアドレスが実際に特定の個人に届く 正しい方法なのか、あるいはその個人に関連付けられたメールボックスに 届くのかさえも明確にすることは不可能なので、これをどう使うかについては とても慎重になる必要があります。

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.

私たちができる最善のアドバイスは、個人のメールアドレスをチェックするのに パスワードを変更するときと同じようにユーザーにアドレスを 二回入力させるというものです。 これによって通常は打ち間違いを防ぐことができます。 二回の入力がマッチしたなら、個人的な内容のメッセージをメールとして そのアドレスへ送ります。 もしメッセージが返ってきて、それがあなたの指示に従っているなら、 それが実際のものであると十分に仮定できます。

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.

より偽造のやりにくい別のやり方に、チェックに対象者に対して PIN (Personal ID Number) を与えるというものがあります。 後の処理のためにアドレスと PIN (ランダムであることが望ましい)を 記録しておくのです。 あなたがメールを送るときに、宛て先人に対して彼らの出すリプライに PIN を含めるように依頼するのです。 しかしそれがそのまま返ってきたり、あるいは返ってきたメッセージが "vacation" スクリプトを通じてのものであっても、そのまま PIN が 含まれてしまいます。 ですから、最善なやり方はメールを送るときに返事には文字を逆順にするとか、 各桁に対して足し算や引き算を行うなどして PIN を変形したものを含めて返すように依頼するという方法です。

MIME/BASE64 文字列のデコードを行うには?

The MIME-Base64 package (available from CPAN) handles this as well as the MIME/QP encoding. Decoding BASE64 becomes as simple as:

MIME-Base64 パッケージ(CPAN で入手可能です)はこの問題と、 MIME/QP エンコーディングを取り扱います。 BASE64 のデコードは以下のように単純です:

        use MIME::Base64;
        $decoded = decode_base64($encoded);

The MIME-Tools package (available from CPAN) supports extraction with decoding of BASE64 encoded attachments and content directly from email messages.

MIME-Tools パッケージ (CPAN にあります) は BASE64 エンコードされた 添付ファイルと本文をメールのメッセージから直接抽出できます。

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:

もしデコードしたい文字列が短い(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

ユーザーのメールアドレスを返すには?

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:

getpwuid をサポートしているシステムであれば、$< という変数と Sys::Hostname モジュール(標準の perl 配布キットの一部です)を使って 以下のようなことが試せるでしょう。

        use Sys::Hostname;
        $address = sprintf('%s@%s', scalar getpwuid($<), hostname);

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.

会社のメールアドレスに関するポリシーが、これが生成するアドレスは その会社のメールシステムが受け付けないものである可能性があります。 ですから、ユーザーに、そのユーザーのメールアドレスを尋ねるべきでしょう。 それに加え、Perl が動作する全てのシステムで この情報が(UNIX と同じように)得られるわけではありません。

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.

CPAN にある Mail::Util モジュール (MailTools パッケージの一部です)は メールアドレスがそのユーザーのものであるかどうかを確かめようとする mailaddress() という関数を提供しています。 これは上で例示したやり方よりも賢く、モジュールがインストールされたときの 情報を使いますが、それでも正しくない可能性があります。 くり返しますが、最善の方法はユーザーに尋ねること、というのがほとんどです。

メールを送るには?

Use the sendmail program directly:

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";

The -oi option prevents sendmail from interpreting a line consisting of a single dot as "end of message". The -t option says to use the headers to decide who to send the message to, and -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.

-oi オプションは sendmail がドットだけの行を“メッセージの終わり”と みなさないようにするためのオプションです。 -tオプションはメッセージを誰に送るかを決めるかのために ヘッダーを使うことを指示し、-odq オプションメッセージを キューに入れることを指示します。 最後のオプションの意味は、あなたのメッセージがすぐには配送されないことを 意味します。 ですから、すぐに配送させたいのであればこのオプションを取り除いてください。

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.

あるいは、直接 mail (mailx と呼ばれることもあります)を呼びだしたり、 単純に 25 番ポートを使ってリモートの SMTP デーモン(多分 sendmail でしょう) との間で詳細な通信を行うといったあまり便利でない方法もあります。

Or you might be able use the CPAN module Mail::Mailer:

あるいは 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();

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.

Mail::Internet モジュールは Mail::Mailer より UNIX 的ではない Net::SMTP を使っていますが、信頼性も低いです。 生の SMTP コマンドを無視します。 sendmail のような mail transport agent を使う理由はたくさんあります。 その中にはキューイングも含まれますし、MX レコードやセキュリティと いったものが含まれます。

メールメッセージに添付するためにどうやって MIME を使えばいいですか?

This answer is extracted directly from the MIME::Lite documentation. Create a multipart message (i.e., one with attachments).

この回答は MIME::Lite のドキュメントから直接持ってきたものです。 マルチパートメッセージ(つまり 添付つきのメッセージ) を作ります。

        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;

MIME::Lite also includes a method for sending these things.

MIME::Lite はまたこれらのものを送るためのメソッドを含みます。

        $msg->send;

This defaults to using sendmail but can be customized to use SMTP via Net::SMTP.

これはデフォルトでは sendmail を使いますが、 Net::SMTP 経由で SMTP を使うようにカスタマイズできます。

メールを読み出すには?

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.

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];
        }

Or more succinctly,

あるいはもっと簡潔に:

        #!/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) ] }

私のホスト名/ドメイン名/IP アドレスを見つけるには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

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.

perl5.7.3 から標準配布されている Net::Domain モジュールを使うと、 完全修飾ドメイン名 (FQDN)、ホスト名、ドメイン名が得られます。

        use Net::Domain qw(hostname hostfqdn hostdomain);

        my $host = hostfqdn();

The Sys::Hostname module, included in the standard distribution since perl5.6, can also get the hostname.

perl5.6 から標準配布されている Sys::Hostname モジュールでも ホスト名を得られます。

        use Sys::Hostname;

        $host = hostname();

To get the IP address, you can use the 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 inet_ntoa function from the Socket module, which also comes with perl.

IP アドレスを得るには、名前から数値に変換するために gethostbyname 組み込み関数が使えます。 数値を、ほとんどの人が想定しているピリオド付きの形 (a.b.c.d) に変換するには、 標準配布されている Socket モジュールの inet_ntoa 関数を使います。

        use Socket;

        my $address = inet_ntoa(
                scalar gethostbyname( $host || 'localhost' )
                );

ニュースの記事やアクティブなニュースグループを取得するには?

Use the Net::NNTP or News::NNTPClient modules, both available from CPAN. This can make tasks like fetching the newsgroup list as simple as

Net::NNTP モジュールか News::NNTPClient モジュールのいずれかを使います。 これらは両方とも CPAN から入手可能です。 これらは以下のように簡単にニュースグループのリストを取得するような 作業ができます。

        perl -MNews::NNTPClient
          -e 'print News::NNTPClient->new->list("newsgroups")'

FTP ファイルをダウンロード/アップロードするには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

The LWP family of modules (available on CPAN as the libwww-perl distribution) can work with FTP just like it can with many other protocols. LWP::Simple makes it quite easy to fetch a file:

LWP モジュールファミリー (CPAN で libwww-perl 配布として利用可能です) は FTP をその他のプロトコルと同様に扱えます。 LWP::Simple はファイルをダウンロードするのをとても簡単にします:

        use LWP::Simple;

        my $data = get( 'ftp://some.ftp.site/some/file.txt' );

If you want more direct or low-level control of the FTP process, you can use the Net::FTP module (in the Standard Library since Perl 5.8). It's documentation has examples showing you just how to do that.

FTP 処理をより直接的に、あるいは低レベルの制御がしたいなら、(Perl 5.8 以降 標準ライブラリに入っている) Net::FTP モジュールが使えます。 その文書にはこれを行う方法を示すための例が載っています。

Perl で RPC を行うには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

Use one of the RPC modules you can find on CPAN ( http://search.cpan.org/search?query=RPC&mode=all ).

CPAN ( http://search.cpan.org/search?query=RPC&mode=all ) で見付かる RFC モジュールの一つを使いましょう。

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.