=encoding euc-jp =head1 NAME =begin original perlintro -- a brief introduction and overview of Perl =end original perlintro -- Perl の概要 =head1 DESCRIPTION =begin original This document is intended to give you a quick overview of the Perl programming language, along with pointers to further documentation. It is intended as a "bootstrap" guide for those who are new to the language, and provides just enough information for you to be able to read other peoples' Perl and understand roughly what it's doing, or write your own simple scripts. =end original この文書は Perl プログラミング言語の簡単な概要を伝えて、更なる 文書へのポインタを示すことを目的としています。 これはこの言語を知らない人のためへの「自習」ガイドを目的としていて、 他の人の Perl を読んで何をしているかを大まかに理解したり、 自分自身で簡単なスクリプトを書くことができるようになるために 十分な情報を提供しています。 =begin original This introductory document does not aim to be complete. It does not even aim to be entirely accurate. In some cases perfection has been sacrificed in the goal of getting the general idea across. You are I advised to follow this introduction with more information from the full Perl manual, the table of contents to which can be found in L. =end original この導入文書は完全性を目的とはしていません。 完全な正確性すらも目的にしていません。 場合によっては、一般的な考え方を得るというゴールのために正確性を犠牲にしています。 この概要を読んだ後、完全な Perl マニュアル(目次は L にあります)から さらなる情報を得ることをI<強く> 勧めます。 =begin original Throughout this document you'll see references to other parts of the Perl documentation. You can read that documentation using the C command or whatever method you're using to read this document. =end original この文書のあちこちに、他の Perl 文書のへの参照があります。 これらの文書は、C コマンドや、この文書を読むために使っている 方法を使って読むことができます。 =begin original Throughout Perl's documentation, you'll find numerous examples intended to help explain the discussed features. Please keep in mind that many of them are code fragments rather than complete programs. =end original Perl の文書のあちこちに、議論している機能の説明を助けることを意図した たくさんの例があります。 これらの多くは完全なプログラムではなく、コード片であることに 留意してください。 =begin original These examples often reflect the style and preference of the author of that piece of the documentation, and may be briefer than a corresponding line of code in a real program. Except where otherwise noted, you should assume that C and C statements appear earlier in the "program", and that any variables used have already been declared, even if those declarations have been omitted to make the example easier to read. =end original これらの例はしばしば文書の作者のスタイルと好みを反映していて、 実際のプログラムでの対応するコードよりもより簡潔かも知れません。 特に記述のない限り、「プログラム」の前に C と C の 文があって、全ての変数は既に宣言されていると仮定するべきです; たとえ例を読みやすくするためにこれらの宣言が省略されていてもです。 =begin original Do note that the examples have been written by many different authors over a period of several decades. Styles and techniques will therefore differ, although some effort has been made to not vary styles too widely in the same sections. Do not consider one style to be better than others - "There's More Than One Way To Do It" is one of Perl's mottos. After all, in your journey as a programmer, you are likely to encounter different styles. =end original 例は数十年の期間にわたって多くの異なった作者によって書かれていることに 注意してください。 従って、スタイルとテクニックは異なりますが、同じ節であまりにも 幅広い異なったスタイルにならないように努力はされています。 あるスタイルが他の物より優れていると考えないでください - 「やり方は一つじゃない」が Perl のモットーです。 結局の所、プログラマとしての旅の途中で、異なったスタイルに出会う ことになります。 =head2 What is Perl? (Perl って何?) =begin original Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more. =end original Perl は、元々テキスト操作のために開発されましたが、今では システム管理、ウェブ開発、ネットワークプログラミング、GUI 開発などを 含む広い範囲で使われている汎用プログラミング言語です。 =begin original The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal). Its major features are that it's easy to use, supports both procedural and object-oriented (OO) programming, has powerful built-in support for text processing, and has one of the world's most impressive collections of third-party modules. =end original この言語は、綺麗さ (小規模、エレガント、最少) ではなく、 実用性 (使い易さ、効率、完全性) を目指しています。 主な機能は、簡単に使える、手続き的とオブジェクト指向 (OO) の両方で プログラミングできる、テキスト処理のための強力な組み込み機能がある、 世界でもっともめざましいサードパーティモジュールのコレクションがある、と いったことです。 =begin original Different definitions of Perl are given in L, L and no doubt other places. From this we can determine that Perl is different things to different people, but that lots of people think it's at least worth writing about. =end original Perl の異なった定義は L と L にあり、きっと他の 場所にもあります。 ここから、Perl は色々な人によって色々な定義ができますが、多くの人々は 少なくとも書く価値があると考えています。 =head2 Running Perl programs (Perl プログラムの実行) =begin original To run a Perl program from the Unix command line: =end original Unix コマンドラインから Perl プログラムを実行するには: perl progname.pl =begin original Alternatively, put this as the first line of your script: =end original あるいは、スクリプトの先頭行に以下のように書いておいて: #!/usr/bin/env perl =begin original ... and run the script as F. Of course, it'll need to be executable first, so C (under Unix). =end original …そしてスクリプトを F として実行します。 もちろん、このためには先に (Unix では) C のようにして、 実行可能にする必要があります。 =begin original (This start line assumes you have the B program. You can also put directly the path to your perl executable, like in C<#!/usr/bin/perl>). =end original (この開始行は、B プログラムがあることを仮定しています。 C<#!/usr/bin/perl> のように、perl 実行ファイルへのパスを直接 書くこともできます)。 =begin original For more information, including instructions for other platforms such as Windows and Mac OS, read L. =end original Windows や Mac OS のような他のプラットホームでの説明を含む、さらなる 情報については、L を読んでください。 =head2 Safety net (セーフティネット) =begin original Perl by default is very forgiving. In order to make it more robust it is recommended to start every program with the following lines: =end original Perl はデフォルトでは非常に寛大です。 より堅牢にするには、全てのプログラムの先頭に以下の行を書くことが 推奨されています: #!/usr/bin/perl use strict; use warnings; =begin original The two additional lines request from perl to catch various common problems in your code. They check different things so you need both. A potential problem caught by C will cause your code to stop immediately when it is encountered, while C will merely give a warning (like the command-line switch B<-w>) and let your code run. To read more about them check their respective manual pages at L and L. =end original 追加した 2 行は、コードにある様々な一般的な問題を捕らえるように perl に 要求します。 この 2 行は別のことをチェックするので、両方が必要です。 C によって捕捉される潜在的な問題は、コードに発見されると 直ちに停止する一方、C は (コマンドラインオプション B<-w> と同様) 警告を出すだけで、コードは実行されます。 これらに関するさらなる情報は、L と L にあるそれぞれの マニュアルページをチェックしてください。 =head2 Basic syntax overview (基本的な文法の概要) =begin original A Perl script or program consists of one or more statements. These statements are simply written in the script in a straightforward fashion. There is no need to have a C function or anything of that kind. =end original Perl スクリプトあるいはプログラムは 1 行以上の文で構成されます。 これらの文は直接的な形でスクリプトに書かれます。 C 関数あるいは似たようなものは不要です。 =begin original Perl statements end in a semi-colon: =end original Perl の文はセミコロンで終端されます: print "Hello, world"; =begin original Comments start with a hash symbol and run to the end of the line =end original コメントは # マークで始まり、行末まで続きます: =begin original # This is a comment =end original # これはコメント =begin original Whitespace is irrelevant: =end original 空白は無視されます: print "Hello, world" ; =begin original ... except inside quoted strings: =end original …但しクォートされた文字列の中は例外です: =begin original # this would print with a linebreak in the middle print "Hello world"; =end original # これは途中に改行が入る print "Hello world"; =begin original Double quotes or single quotes may be used around literal strings: =end original ダブルクォートやシングルクォートはリテラル文字列をくくるのに使われます: print "Hello, world"; print 'Hello, world'; =begin original However, only double quotes "interpolate" variables and special characters such as newlines (C<\n>): =end original しかし、ダブルクォートのみが変数と改行(C<\n>)のような特殊文字を 「展開」します: =begin original print "Hello, $name\n"; # works fine print 'Hello, $name\n'; # prints $name\n literally =end original print "Hello, $name\n"; # うまく動作する print 'Hello, $name\n'; # $name\n という文字をそのまま表示する =begin original Numbers don't need quotes around them: =end original 数値はクォートする必要はありません: print 42; =begin original You can use parentheses for functions' arguments or omit them according to your personal taste. They are only required occasionally to clarify issues of precedence. =end original 関数の引数のかっこは、好みで付けたり省略したりできます。 必要なのは、優先順位の問題を明確化するときだけです。 print("Hello, world\n"); print "Hello, world\n"; =begin original More detailed information about Perl syntax can be found in L. =end original Perl の文法に関するさらに詳細な情報は L にあります。 =head2 Perl variable types (Perl の変数型) =begin original Perl has three main variable types: scalars, arrays, and hashes. =end original Perl には三つの主な変数型があります: スカラ、配列、ハッシュです。 =over 4 =item Scalars (スカラ) =begin original A scalar represents a single value: =end original スカラは単一の値を表現します: my $animal = "camel"; my $answer = 42; =begin original Scalar values can be strings, integers or floating point numbers, and Perl will automatically convert between them as required. There is no need to pre-declare your variable types, but you have to declare them using the C keyword the first time you use them. (This is one of the requirements of C.) =end original スカラ値には文字列、整数、浮動小数点数があり、Perl は必要なときに自動的に これらの値を相互に変換します。 変数型を事前に宣言する必要はありませんが、変数を使うときには C キーワードを使って宣言する必要があります。 (これは C が要求することの一つです。) =begin original Scalar values can be used in various ways: =end original スカラ値は色々な方法で利用できます: print $animal; print "The animal is $animal\n"; print "The square of $answer is ", $answer * $answer, "\n"; =begin original There are a number of "magic" scalars with names that look like punctuation or line noise. These special variables are used for all kinds of purposes, and are documented in L. The only one you need to know about for now is C<$_> which is the "default variable". It's used as the default argument to a number of functions in Perl, and it's set implicitly by certain looping constructs. =end original 句読点や回線ノイズのように見える名前を持った、多くの「マジック」変数が あります。 これらの特殊変数はあらゆる目的のために利用され、L に 文書化されています。 今のところ知っておくべきただ一つのことは、「デフォルト変数」である C<$_> です。 これは Perl の多くの関数でデフォルト引数として使われ、ある種のループ構造で 暗黙に設定されます。 =begin original print; # prints contents of $_ by default =end original print; # デフォルトで $_ の内容を表示する =item Arrays (配列) =begin original An array represents a list of values: =end original 配列は値のリストを表現します: my @animals = ("camel", "llama", "owl"); my @numbers = (23, 42, 69); my @mixed = ("camel", 42, 1.23); =begin original Arrays are zero-indexed. Here's how you get at elements in an array: =end original 配列は添え字 0 から始まります。 以下は配列の要素を取得する方法です: =begin original print $animals[0]; # prints "camel" print $animals[1]; # prints "llama" =end original print $animals[0]; # "camel" を表示する print $animals[1]; # "llama" を表示する =begin original The special variable C<$#array> tells you the index of the last element of an array: =end original 特殊変数 C<$#array> は、配列の最後の要素の添え字を返します: =begin original print $mixed[$#mixed]; # last element, prints 1.23 =end original print $mixed[$#mixed]; # 最後の要素である 1.23 を表示する =begin original You might be tempted to use C<$#array + 1> to tell you how many items there are in an array. Don't bother. As it happens, using C<@array> where Perl expects to find a scalar value ("in scalar context") will give you the number of elements in the array: =end original 配列にある要素の数を知るのに C<$#array + 1> を使いたくなるかも知れません。 心配はいりません。 偶然にも、Perl がスカラ値を想定しているところ(「スカラコンテキスト」)で C<@array> を使うと、配列の要素の数を返します: if (@animals < 5) { ... } =begin original The elements we're getting from the array start with a C<$> because we're getting just a single value out of the array; you ask for a scalar, you get a scalar. =end original 配列から一つの値を取り出したいだけなので、配列の要素は C<$> で始まります; スカラを得ようとすれば、スカラを得ます。 =begin original To get multiple values from an array: =end original 配列から複数の値を得るには: =begin original @animals[0,1]; # gives ("camel", "llama"); @animals[0..2]; # gives ("camel", "llama", "owl"); @animals[1..$#animals]; # gives all except the first element =end original @animals[0,1]; # ("camel", "llama") を返す @animals[0..2]; # ("camel", "llama", "owl") を返す @animals[1..$#animals]; # 最初の要素以外全てを返す =begin original This is called an "array slice". =end original これは「配列スライス」と呼ばれます。 =begin original You can do various useful things to lists: =end original リストに対して色々便利なことが出来ます: my @sorted = sort @animals; my @backwards = reverse @numbers; =begin original There are a couple of special arrays too, such as C<@ARGV> (the command line arguments to your script) and C<@_> (the arguments passed to a subroutine). These are documented in L. =end original C<@ARGV> (スクリプトのコマンドライン引数) や C<@_> (サブルーチンに渡された 引数) のように、色々な特殊配列もあります。 これらは L に文書化されています。 =item Hashes (ハッシュ) =begin original A hash represents a set of key/value pairs: =end original ハッシュはキー/値の組の集合を表現します: my %fruit_color = ("apple", "red", "banana", "yellow"); =begin original You can use whitespace and the C<< => >> operator to lay them out more nicely: =end original より見やすくするために、空白と C<< => >> 演算子が使えます: my %fruit_color = ( apple => "red", banana => "yellow", ); =begin original To get at hash elements: =end original ハッシュの要素を得るには: =begin original $fruit_color{"apple"}; # gives "red" =end original $fruit_color{"apple"}; # "red" を返す =begin original You can get at lists of keys and values with C and C. =end original キーのリストと値のリストは C と C で得られます。 my @fruits = keys %fruit_colors; my @colors = values %fruit_colors; =begin original Hashes have no particular internal order, though you can sort the keys and loop through them. =end original ハッシュには特に決まった順序はありませんが、キーをソートして、 それを使ってループできます。 =begin original Just like special scalars and arrays, there are also special hashes. The most well known of these is C<%ENV> which contains environment variables. Read all about it (and other special variables) in L. =end original 特殊スカラおよび配列と同様、特殊ハッシュもあります。 そのうち最もよく知られているものは、環境変数が入っている C<%ENV> です。 これら全て (およびその他の特殊変数) は L にあります。 =back =begin original Scalars, arrays and hashes are documented more fully in L. =end original スカラ、配列、ハッシュについては L により完全に 文書化されています。 =begin original More complex data types can be constructed using references, which allow you to build lists and hashes within lists and hashes. =end original より複雑なデータ型は、リストやハッシュの中にリストやハッシュを 入れることができるリファレンスを使って構築できます。 =begin original A reference is a scalar value and can refer to any other Perl data type. So by storing a reference as the value of an array or hash element, you can easily create lists and hashes within lists and hashes. The following example shows a 2 level hash of hash structure using anonymous hash references. =end original リファレンスはスカラ値で、任意の他の Perl データを参照できます。 従って、リファレンスを配列やハッシュの値として格納することで、 リストやハッシュの中に簡単にリストやハッシュを作成できます。 以下の例は、無名ハッシュリファレンスを使った 2 レベルのハッシュのハッシュを 説明しています: my $variables = { scalar => { description => "single item", sigil => '$', }, array => { description => "ordered list of items", sigil => '@', }, hash => { description => "key/value pairs", sigil => '%', }, }; print "Scalars begin with a $variables->{'scalar'}->{'sigil'}\n"; =begin original Exhaustive information on the topic of references can be found in L, L, L and L. =end original リファレンスに関する包括的な情報は、 L, L, L, L にあります。 =head2 Variable scoping (変数のスコープ) =begin original Throughout the previous section all the examples have used the syntax: =end original 前述した章の全体で、全ての例は以下の文法を使っています: my $var = "value"; =begin original The C is actually not required; you could just use: =end original C は実際には必要ではありません; 単に以下のようにも使えます: $var = "value"; =begin original However, the above usage will create global variables throughout your program, which is bad programming practice. C creates lexically scoped variables instead. The variables are scoped to the block (i.e. a bunch of statements surrounded by curly-braces) in which they are defined. =end original しかし、上述の使用法はプログラム全体でグローバルな変数を作ることになり、 これは悪いプログラミング手法です。 代わりに、C はレキシカルなスコープを持った変数を作ります。 変数は、宣言されたブロック (中かっこで囲まれた文のかたまり) 内の スコープを持ちます。 =begin original my $x = "foo"; my $some_condition = 1; if ($some_condition) { my $y = "bar"; print $x; # prints "foo" print $y; # prints "bar" } print $x; # prints "foo" print $y; # prints nothing; $y has fallen out of scope =end original my $x = "foo"; my $some_condition = 1; if ($some_condition) { my $y = "bar"; print $x; # "foo" を表示する print $y; # "bar" を表示する } print $x; # "foo" を表示する print $y; # 何も表示しない; $y はスコープ外 =begin original Using C in combination with a C at the top of your Perl scripts means that the interpreter will pick up certain common programming errors. For instance, in the example above, the final C would cause a compile-time error and prevent you from running the program. Using C is highly recommended. =end original Perl スクリプトの先頭に C を書くことと合わせて C を 使うことによって、インタプリタがある種のよくあるプログラミングミスを 検出できます。 例えば、上述の例で、最後の C はコンパイルエラーとなり、 プログラムの実行を妨げます。 C を使うことを強く勧めます。 =head2 Conditional and looping constructs (条件とループ構造) =begin original Perl has most of the usual conditional and looping constructs. As of Perl 5.10, it even has a case/switch statement (spelled C/C). See L for more details. =end original Perl には、一般的な条件構文とループ構文のほとんど全てがあります。 Perl 5.10 から、case/switch 文もあります (C/C と綴ります)。 さらなる詳細については L を参照してください。 =begin original The conditions can be any Perl expression. See the list of operators in the next section for information on comparison and boolean logic operators, which are commonly used in conditional statements. =end original 任意の Perl 式は条件となります。 条件文でよく使われる、比較演算子と真偽値論理演算子に関する情報については、 次の節にある演算子の一覧を参照してください。 =over 4 =item if if ( condition ) { ... } elsif ( other condition ) { ... } else { ... } =begin original There's also a negated version of it: =end original これの否定版もあります: unless ( condition ) { ... } =begin original This is provided as a more readable version of C)>. =end original これは、C)> をより読みやすくしたものです。 =begin original Note that the braces are required in Perl, even if you've only got one line in the block. However, there is a clever way of making your one-line conditional blocks more English like: =end original たとえブロック中に 1 行しかなくても、Perl では中かっこが必要であることに 注意してください。 しかし、1 行の条件ブロックをより英語風にする気の利いた方法があります: =begin original # the traditional way if ($zippy) { print "Yow!"; } =end original # 伝統的な方法 if ($zippy) { print "Yow!"; } =begin original # the Perlish post-condition way print "Yow!" if $zippy; print "We have no bananas" unless $bananas; =end original # Perl っぽい後置条件 print "Yow!" if $zippy; print "We have no bananas" unless $bananas; =item while while ( condition ) { ... } =begin original There's also a negated version, for the same reason we have C: =end original C があるのと同じ理由で、これにも否定版があります。 until ( condition ) { ... } =begin original You can also use C in a post-condition: =end original C を後置条件にも使えます: =begin original print "LA LA LA\n" while 1; # loops forever =end original print "LA LA LA\n" while 1; # 無限ループ =item for =begin original Exactly like C: =end original 完全に C と同様です: for ($i = 0; $i <= $max; $i++) { ... } =begin original The C style for loop is rarely needed in Perl since Perl provides the more friendly list scanning C loop. =end original C 形式のループは Perl ではめったに必要ではありません; なぜなら Perl は より親切なリストスキャンである C ループがあるからです。 =item foreach foreach (@array) { print "This element is $_\n"; } print $list[$_] foreach 0 .. $max; =begin original # you don't have to use the default $_ either... foreach my $key (keys %hash) { print "The value of $key is $hash{$key}\n"; } =end original # デフォルトの $_ を使う必要はない… foreach my $key (keys %hash) { print "The value of $key is $hash{$key}\n"; } =begin original The C keyword is actually a synonym for the C keyword. See C>. =end original C キーワードは実際には C キーワードの別名です。 C> を参照してください。 =back =begin original For more detail on looping constructs (and some that weren't mentioned in this overview) see L. =end original ループ構造に関するさらなる詳細 (およびこの概説で触れていないこと) に ついては L を参照してください。 =head2 Builtin operators and functions (組み込みの演算子と関数) =begin original Perl comes with a wide selection of builtin functions. Some of the ones we've already seen include C, C and C. A list of them is given at the start of L and you can easily read about any given function by using C>. =end original Perl は幅広い組み込み関数を持っています。 C, C, C など、その一部は既に見てきました。 その一覧は L の先頭にあり、関数の説明は C> とすることで簡単に読むことができます。 =begin original Perl operators are documented in full in L, but here are a few of the most common ones: =end original Perl の演算子は L に完全に文書化されていますが、もっとも 一般的なものをいくつか以下に示します: =over 4 =item Arithmetic (数値演算) =begin original + addition - subtraction * multiplication / division =end original + 加算 - 減算 * 乗算 / 除算 =item Numeric comparison (数値比較) =begin original == equality != inequality < less than > greater than <= less than or equal >= greater than or equal =end original == 相等 != 不等 < より小さい > より大きい <= 以下 >= 以上 =item String comparison (文字列比較) =begin original eq equality ne inequality lt less than gt greater than le less than or equal ge greater than or equal =end original eq 相等 ne 不等 lt より小さい gt より大きい le 以下 ge 以上 =begin original (Why do we have separate numeric and string comparisons? Because we don't have special variable types, and Perl needs to know whether to sort numerically (where 99 is less than 100) or alphabetically (where 100 comes before 99). =end original (どうして数値比較と文字列比較が分かれているのでしょう? なぜなら、特別な変数型はないので、数値として扱う (99 は 100 より小さい) か、文字として扱う (100 は 99 の前) かを Perl に知らせる必要があるからです)。 =item Boolean logic (真偽値論理) && and || or ! not =begin original (C, C and C aren't just in the above table as descriptions of the operators. They're also supported as operators in their own right. They're more readable than the C-style operators, but have different precedence to C<&&> and friends. Check L for more detail.) =end original (C, C, C は演算子の記述としては上述の表にはありません。 これらも本来の演算子として対応しています。 これらは C 形式の演算子より読みやすいですが、C<&&> およびその仲間とは 異なった優先順位を持ちます。 さらなる詳細については L を参照してください。) =item Miscellaneous (その他) =begin original = assignment . string concatenation x string multiplication .. range operator (creates a list of numbers or strings) =end original = 代入 . 文字列結合 x 文字列乗算 .. 範囲演算子 (数値や文字列のリストを作る) =back =begin original Many operators can be combined with a C<=> as follows: =end original 多くの演算子は、以下のように C<=> と組み合わせることができます: =begin original $a += 1; # same as $a = $a + 1 $a -= 1; # same as $a = $a - 1 $a .= "\n"; # same as $a = $a . "\n"; =end original $a += 1; # $a = $a + 1 と同じ $a -= 1; # $a = $a - 1 と同じ $a .= "\n"; # $a = $a . "\n"; と同じ =head2 Files and I/O (ファイルと I/O) =begin original You can open a file for input or output using the C function. It's documented in extravagant detail in L and L, but in short: =end original C 関数を使って、入力や出力のためにファイルを開けます。 L と L に非常に詳細に文書化されていますが、 簡単には: open(my $in, "<", "input.txt") or die "Can't open input.txt: $!"; open(my $out, ">", "output.txt") or die "Can't open output.txt: $!"; open(my $log, ">>", "my.log") or die "Can't open my.log: $!"; =begin original You can read from an open filehandle using the C<< <> >> operator. In scalar context it reads a single line from the filehandle, and in list context it reads the whole file in, assigning each line to an element of the list: =end original C<< <> >> 演算子を使って、開いているファイルハンドルから読み込めます。 スカラコンテキストではファイルハンドルから 1 行を読み込み、リスト コンテキストではファイル全体を読み込んで、それぞれの行をリストの要素に 代入します: my $line = <$in>; my @lines = <$in>; =begin original Reading in the whole file at one time is called slurping. It can be useful but it may be a memory hog. Most text file processing can be done a line at a time with Perl's looping constructs. =end original ファイル全体を一度に読み込むことは「吸い込み」(slurping) と呼ばれます。 これは便利ですが、メモリを占有するかもしれません。 ほとんどのテキストファイル処理は、Perl のループ構文を使って 1 行ずつ処理できます。 =begin original The C<< <> >> operator is most often seen in a C loop: =end original C<< <> >> 演算子は、C ループの中でもっともよく見られます: =begin original while (<$in>) { # assigns each line in turn to $_ print "Just read in this line: $_"; } =end original while (<$in>) { # それぞれの行を $_ に代入する print "Just read in this line: $_"; } =begin original We've already seen how to print to standard output using C. However, C can also take an optional first argument specifying which filehandle to print to: =end original C を使って標準出力に出力する方法はすでに見てきました。 しかし、C はオプションとして、どのファイルハンドルに出力するかを 指定する第一引数を取ることもできます: print STDERR "This is your final warning.\n"; print $out $record; print $log $logmessage; =begin original When you're done with your filehandles, you should C them (though to be honest, Perl will clean up after you if you forget): =end original ファイルハンドルを使ったら、C を使うべきです (しかし正直に言うと、もしあなたが忘れても Perl はあなたの後始末をします): close $in or die "$in: $!"; =head2 Regular expressions (正規表現) =begin original Perl's regular expression support is both broad and deep, and is the subject of lengthy documentation in L, L, and elsewhere. However, in short: =end original Perl の正規表現サポートは広く深く、長い文書は L, L およびどこにでもあります。 しかし、短く言うと: =over 4 =item Simple matching (単純なマッチング) =begin original if (/foo/) { ... } # true if $_ contains "foo" if ($a =~ /foo/) { ... } # true if $a contains "foo" =end original if (/foo/) { ... } # $_ に "foo" が含まれていれば真 if ($a =~ /foo/) { ... } # $a に "foo" が含まれていれば真 =begin original The C matching operator is documented in L. It operates on C<$_> by default, or can be bound to another variable using the C<=~> binding operator (also documented in L). =end original C マッチング演算子は L に文書化されています。 これはデフォルトでは C<$_> を操作しますし、C<=~> 結合演算子 (これも L で文書化されています) を使って他の変数に対して 適用することもできます。 =item Simple substitution (単純な置換) =begin original s/foo/bar/; # replaces foo with bar in $_ $a =~ s/foo/bar/; # replaces foo with bar in $a $a =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar # in $a =end original s/foo/bar/; # $_ にある foo を bar に置き換える $a =~ s/foo/bar/; # $a にある foo を bar に置き換える $a =~ s/foo/bar/g; # $a にある全ての foo を bar に置き換える =begin original The C substitution operator is documented in L. =end original C 置換演算子は L に文書化されています。 =item More complex regular expressions (より複雑な正規表現) =begin original You don't just have to match on fixed strings. In fact, you can match on just about anything you could dream of by using more complex regular expressions. These are documented at great length in L, but for the meantime, here's a quick cheat sheet: =end original 単に固定した文字列にマッチングさせる必要はありません。 実際の所、より複雑な正規表現を使うことによって、思い付く限りほとんど 全てのものとマッチングさせることが出来ます。 これらは L に長文で文書化されていますが、今のところは、以下に カンニングペーパーを示します: =begin original . a single character \s a whitespace character (space, tab, newline, ...) \S non-whitespace character \d a digit (0-9) \D a non-digit \w a word character (a-z, A-Z, 0-9, _) \W a non-word character [aeiou] matches a single character in the given set [^aeiou] matches a single character outside the given set (foo|bar|baz) matches any of the alternatives specified =end original . 単一の文字 \s 空白文字(空白、タブ、改行…) \S 非空白文字 \d 数字 (0-9) \D 非数字 \w 単語文字 (a-z, A-Z, 0-9, _) \W 非単語文字 [aeiou] 指定された集合に含まれる単一の文字 [^aeiou] 指定された集合に含まれない単一の文字 (foo|bar|baz) 指定された代替のいずれかにマッチング =begin original ^ start of string $ end of string =end original ^ 文字列の先頭 $ 文字列の末尾 =begin original Quantifiers can be used to specify how many of the previous thing you want to match on, where "thing" means either a literal character, one of the metacharacters listed above, or a group of characters or metacharacters in parentheses. =end original 量指定子は直前に指定したマッチングさせたいものを何回マッチングさせたいかを 指定するために使います; ここで「もの」というのはリテラルな 1 文字、 上述したメタ文字の一つ、かっこに囲まれた文字やメタ文字のグループです。 =begin original * zero or more of the previous thing + one or more of the previous thing ? zero or one of the previous thing {3} matches exactly 3 of the previous thing {3,6} matches between 3 and 6 of the previous thing {3,} matches 3 or more of the previous thing =end original * 手前にあるものに 0 回以上マッチング + 手前にあるものに 1 回以上マッチング ? 手前にあるものに 1 回または 0 回マッチング {3} 手前にあるものにちょうど 3 回マッチング {3,6} 手前にあるものに 3 回から 6 回マッチング {3,} 手前にあるものに 3 回以上マッチング =begin original Some brief examples: =end original いくつかの簡単な例です: =begin original /^\d+/ string starts with one or more digits /^$/ nothing in the string (start and end are adjacent) /(\d\s){3}/ three digits, each followed by a whitespace character (eg "3 4 5 ") /(a.)+/ matches a string in which every odd-numbered letter is a (eg "abacadaf") =end original /^\d+/ 一つ以上の数字で始まる /^$/ 空文字列 (先頭と末尾が隣接している) /(\d\s){3}/ 3 桁の数字(それぞれに空白文字が引き続く) (例えば "3 4 5 ") /(a.)+/ 奇数番目が全て a である文字列 (例えば "abacadaf") =begin original # This loop reads from STDIN, and prints non-blank lines: while (<>) { next if /^$/; print; } =end original # このループは STDIN から読み込み、非空行を表示する: while (<>) { next if /^$/; print; } =item Parentheses for capturing (かっこと捕捉) =begin original As well as grouping, parentheses serve a second purpose. They can be used to capture the results of parts of the regexp match for later use. The results end up in C<$1>, C<$2> and so on. =end original かっこは、グループ化だけではなく第二の目的の役目を果たします。 正規表現マッチングの一部の結果を後で使うために捕捉するために使えます。 結果は C<$1>, C<$2> などに入ります。 =begin original # a cheap and nasty way to break an email address up into parts =end original # e メールアドレスをパーツに分解するちゃちで扱いにくい方法 if ($email =~ /([^@]+)@(.+)/) { print "Username is $1\n"; print "Hostname is $2\n"; } =item Other regexp features (その他の正規表現の機能) =begin original Perl regexps also support backreferences, lookaheads, and all kinds of other complex details. Read all about them in L, L, and L. =end original Perl の正規表現は、後方参照、前方参照およびその他のあらゆる種類の複雑な 詳細に対応しています。 L, L, L でこれらに関する全てを読んでください。 =back =head2 Writing subroutines (サブルーチンを書く) =begin original Writing subroutines is easy: =end original サブルーチンを書くのは簡単です: sub logger { my $logmessage = shift; open my $logfile, ">>", "my.log" or die "Could not open my.log: $!"; print $logfile $logmessage; } =begin original Now we can use the subroutine just as any other built-in function: =end original これでサブルーチンをその他の組み込み関数と同様に使えます: logger("We have a logger subroutine!"); =begin original What's that C? Well, the arguments to a subroutine are available to us as a special array called C<@_> (see L for more on that). The default argument to the C function just happens to be C<@_>. So C shifts the first item off the list of arguments and assigns it to C<$logmessage>. =end original C とはなんでしょう? ええっと、サブルーチンの引数は C<@_> と呼ばれる特殊配列として利用可能に なります (これに関する詳細は L を参照してください)。 C 関数のデフォルト引数は たまたま C<@_> です。 それで、C は引数のリストの最初のものを取り出して、 C<$logmessage> に代入します。 =begin original We can manipulate C<@_> in other ways too: =end original その他の方法でも C<@_> を操作できます: =begin original my ($logmessage, $priority) = @_; # common my $logmessage = $_[0]; # uncommon, and ugly =end original my ($logmessage, $priority) = @_; # 一般的 my $logmessage = $_[0]; # 一般的でもなく、美しくもない =begin original Subroutines can also return values: =end original サブルーチンは値を返すこともできます: sub square { my $num = shift; my $result = $num * $num; return $result; } =begin original Then use it like: =end original それからこういう風に使います: $sq = square(8); =begin original For more information on writing subroutines, see L. =end original サブルーチンの書き方に関するさらなる情報については、L を 参照してください。 =head2 OO Perl (OO Perl) =begin original OO Perl is relatively simple and is implemented using references which know what sort of object they are based on Perl's concept of packages. However, OO Perl is largely beyond the scope of this document. Read L and L. =end original OO Perl は比較的単純で、オブジェクトが Perl の概念であるパッケージの どれに基づいているかを知っているリファレンスを使って実装されています。 しかし、OO Perl はこの文書の範囲からは大きく外れます。 L と L を読んでください。 =begin original As a beginning Perl programmer, your most common use of OO Perl will be in using third-party modules, which are documented below. =end original Perl プログラマを始めるに当たって、OO Perl の最も一般的な使用法は 以下に記述している、サードパーティーモジュールを使うことです。 =head2 Using Perl modules (Perl モジュールを使う) =begin original Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN ( L ). A number of popular modules are included with the Perl distribution itself. =end original Perl モジュールは、車輪の再発明を避けるための様々な機能を提供していて、 CPAN ( L ) からダウンロードできます。 多くの有名なモジュールは Perl 配布自身に含まれています。 =begin original Categories of modules range from text manipulation to network protocols to database integration to graphics. A categorized list of modules is also available from CPAN. =end original モジュールのカテゴリは、テキスト操作からネットワークプロトコル、 データベース統合、グラフィックまで多岐に渡ります。 カテゴリ別モジュールリストも CPAN で利用可能です。 =begin original To learn how to install modules you download from CPAN, read L. =end original CPAN からダウンロードしたモジュールのインストール方法を学ぶには、 L を読んでください。 =begin original To learn how to use a particular module, use C>. Typically you will want to C>, which will then give you access to exported functions or an OO interface to the module. =end original 特定のモジュールの使い方を学ぶには、C> を 使ってください。 典型的には C> として、それからエクスポートされた 関数か、モジュールへの OO インターフェースにアクセスします。 =begin original L contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use. =end original L には多くの一般的なタスクに関する質問と答えがあり、しばしば よい CPAN モジュールの提案が提供されています。 =begin original L describes Perl modules in general. L lists the modules which came with your Perl installation. =end original L は一般的な Perl モジュールについて記述しています。 L は Perl インストール時に同梱されているモジュールの一覧です。 =begin original If you feel the urge to write Perl modules, L will give you good advice. =end original Perl モジュールを作りたいと思ったなら、L がよい助言を 与えてくれるでしょう。 =head1 AUTHOR Kirrily "Skud" Robert =begin meta Translate: SHIRAKATA Kentaro Status: completed =end meta