perlfaq7 > 5.14.1 との差分

perlfaq7 5.14.1 と 5.6.1 の差分

11
22=encoding euc-jp
33
44=head1 NAME
55
66=begin original
77
8perlfaq7 - General Perl Language Issues
8perlfaq7 - Perl Language Issues ($Revision: 1.28 $, $Date: 1999/05/23 20:36:18 $)
99
1010=end original
1111
12perlfaq7 - Perl 言語一般に関することがら
12perlfaq7 - Perlに関することがら ($Revision: 1.28 $, $Date: 1999/05/23 20:36:18 $)
1313
1414=head1 DESCRIPTION
1515
16=begin original
17
18This section deals with general Perl language issues that don't
19clearly fit into any of the other sections.
20
21=end original
22
2316このセクションでは、他のセクションにはきっちりとあてはまらないような
2417Perl 言語に関する一般的な事柄を扱います。
2518
2619=head2 Can I get a BNF/yacc/RE for the Perl language?
2720
28(Perl のための BNF/yacc/RE は入手できますか?)
21(Perlのための BNF/yacc/RE は入手できますか?)
2922
3023=begin original
3124
3225There is no BNF, but you can paw your way through the yacc grammar in
3326perly.y in the source distribution if you're particularly brave. The
3427grammar relies on very smart tokenizing code, so be prepared to
3528venture into toke.c as well.
3629
3730=end original
3831
3932BNFはありませんが、もし多少の勇気を持ちあわせているのであれば
40配布ソースに含まれている perly.y にある yacc 文法をいじくりまわすことが
33配布ソースに含まれているperly.yにあるyacc文法をいじくりまわすことができます。
41できます。
4234その文法は非常に賢い字句解析ルーチンに依存したものなので、
4335toke.c を眺める準備もしておきましょう。
4436
45=begin original
37Chaim Frenkelの言葉を借りればこうです: “Perlの文法は
38BNF まで縮小(reduce)することができない。
39perl の構文解析の作業は yacc、字句解析器、煙と鏡とに分配される”
4640
47In the words of Chaim Frenkel: "Perl's grammar can not be reduced to BNF.
48The work of parsing perl is distributed between yacc, the lexer, smoke
49and mirrors."
50
51=end original
52
53reduce
54Chaim Frenkel の言葉を借りればこうです:
55「Perl の文法は BNF まで縮小することができない。
56perl の構文解析の作業は yacc、字句解析器、煙と鏡とに分配される。」
57
5841=head2 What are all these $@%&* punctuation signs, and how do I know when to use them?
5942
60($@%&* のマークはなんですか? これらをいつ使えばいいのかを知るにはどうすればいいですか?)
43($@%&* のマークはなんですか?これらをいつ使えばいいのかを知るには
44どうすればいいですか?)
6145
62=begin original
46これらは型指定子(type specifiers)で、L<perldata>で説明されています:
6347
64They are type specifiers, as detailed in L<perldata>:
65
66=end original
67
68これらは型指定子(type specifiers)で、L<perldata> で説明されています:
69
7048=begin original
7149
72 $ for scalar values (number, string or reference)
50 $ for scalar values (number, string or reference)
73 @ for arrays
51 @ for arrays
74 % for hashes (associative arrays)
52 % for hashes (associative arrays)
75 & for subroutines (aka functions, procedures, methods)
53 & for subroutines (aka functions, procedures, methods)
76 * for all types of that symbol name. In version 4 you used them like
54 * for all types of that symbol name. In version 4 you used them like
77 pointers, but in modern perls you can just use references.
55 pointers, but in modern perls you can just use references.
7856
7957=end original
8058
81 $ スカラ値(数値、文字列、リファレンス)に対するもの
59 $ スカラ値(数値、文字列、リファレンス)に対するもの
82 @ 配列に対するもの
60 @ 配列に対するもの
83 % ハッシュ(連想配列)に対するもの
61 % ハッシュ(連想配列)に対するもの
84 & サブルーチン(またの名を関数、手続き、メソッド)に対するもの
62 & サブルーチン(またの名を関数、手続き、メソッド)に対するもの
85 * シンボル名に対する全ての型。バージョン 4 ではポインタのように
63 * シンボル名に対する全ての型。バージョン4ではポインタのように
86 使われていましたが、新しい perl ではリファレンスが使えます。
64 使われていましたが、新しい perl ではリファレンスが使えます。
8765
88=begin original
89
90There are a couple of other symbols that
91you're likely to encounter that aren't
92really type specifiers:
93
94=end original
95
9666実際には型指定子として見ることはないであろう二つのものが
9767この他にもあります:
9868
99=begin original
69 <> あるファイルハンドルからレコードを入力するのに使われます
70 \ なにかのリファレンスを取ります。
10071
101 <> are used for inputting a record from a filehandle.
102 \ takes a reference to something.
103
104=end original
105
106 <> あるファイルハンドルからレコードを入力するのに使われます。
107 \ なにかのリファレンスを取ります。
108
10972=begin original
11073
11174Note that <FILE> is I<neither> the type specifier for files
11275nor the name of the handle. It is the C<< <> >> operator applied
11376to the handle FILE. It reads one line (well, record--see
114L<perlvar/$E<sol>>) from the handle FILE in scalar context, or I<all> lines
77L<perlvar/$/>) from the handle FILE in scalar context, or I<all> lines
11578in list context. When performing open, close, or any other operation
11679besides C<< <> >> on files, or even when talking about the handle, do
11780I<not> use the brackets. These are correct: C<eof(FH)>, C<seek(FH, 0,
118812)> and "copying from STDIN to FILE".
11982
12083=end original
12184
122<FILE> は、ファイルに対する型指定子にもハンドルの名前の
85<FILE>は、ファイルに対する型指定子にもハンドルの名前の
123I<どちらでもない> ということに注意してください。
86I<どちらでもない>ということに注意してください。
124これはハンドル FILE に対する C<< <> >> 演算子です。
87これはハンドル FILE に対する C<< <> >>演算子です。
125一行(そう、レコードですね。L<perlvar/$E<sol>> を参照してください) を
88一行(そう、レコードですね。L<perlvar/$/>を参照してください) を
126FILE というハンドルからスカラコンテキストで読み出します。
89FILE というハンドルからスカラコンテキストで読み出します。
127リストコンテキストの場合は B<全ての> 行を読み出します。
90リストコンテキストの場合はB<全ての>行を読み出します。
128ファイルの C<< <> >> に関係する open、close などの操作を行うときには、
91ファイルの C<< <> >> に関係するopen、closeなどの操作を行うときには、
12992ハンドルについて行っている場合であっても
130アングルブラケットを使っては B<いけません>。
93アングルブラケットを使ってはB<いけません>。
131C<eof(FH)>, C<seek(FH, 0,2)> や "copying from STDIN to FILE" は
94C<eof(FH)>, C<seek(FH, 0,2)> や "copying from STDIN to FILE" は
13295正しいものなのです。
13396
13497=head2 Do I always/never have to quote my strings or use semicolons and commas?
13598
136(文字列では常にクォートする/決してクォートしない必要があるのでしょうか? また、セミコロンやカンマについては?)
99(文字列では 常にクォートする/決してクォートしない 必要があるのでしょうか?
100また、セミコロンやカンマについては?)
137101
138=begin original
139
140Normally, a bareword doesn't need to be quoted, but in most cases
141probably should be (and must be under C<use strict>). But a hash key
142consisting of a simple word and the left-hand
143operand to the C<< => >> operator both
144count as though they were quoted:
145
146=end original
147
148102通常は、裸の単語(barewords)はクォートする必要はありませんが、
149ほとんど場合はクォートすべきでしょう(そして、C<use strcit> しているときは
103ほとんど場合はクォートすべきでしょう(そして、C<use strcit>しているときは
150104しなければなりません)。
151しかし、単純な単語から
105しかし、単純な単語(サブルーチンの名前として定義されていないもの)から
152106構成されるハッシュと、C<< => >> 演算子の左側にあるオペランドは
153107両方ともクォートされているとみなされます:
154108
155 This is like this
109 This is like this
156 ------------ ---------------
110 ------------ ---------------
157 $foo{line} $foo{'line'}
111 $foo{line} $foo{"line"}
158 bar => stuff 'bar' => stuff
112 bar => stuff "bar" => stuff
159113
160=begin original
161
162The final semicolon in a block is optional, as is the final comma in a
163list. Good style (see L<perlstyle>) says to put them in except for
164one-liners:
165
166=end original
167
168114ブロックの最後にあるセミコロンは、リストの最後にあるカンマと同じく
169115省略可能です。
170良いスタイル(L<perlstyle> を参照)は一行野郎(one-liners)でなければ
116良いスタイル(L<perlstyle>を参照)は一行野郎(one-liners)でなければ
171117それらを使うようにしましょうと言っています。
172118
173 if ($whoops) { exit 1 }
119 if ($whoops) { exit 1 }
174 @nums = (1, 2, 3);
120 @nums = (1, 2, 3);
175121
176 if ($whoops) {
122 if ($whoops) {
177 exit 1;
123 exit 1;
178 }
124 }
125 @lines = (
180 @lines = (
181126 "There Beren came from mountains cold",
182127 "And lost he wandered under leaves",
183 );
128 );
184129
185130=head2 How do I skip some return values?
186131
187132(戻り値の一部をスキップするには?)
188133
189=begin original
190
191One way is to treat the return values as a list and index into it:
192
193=end original
194
195134方法の一つは、戻り値をリストとみなして、それに添え字づけするというものです:
196135
197 $dir = (getpwnam($user))[7];
136 $dir = (getpwnam($user))[7];
198137
199=begin original
138もう一つのやりかたは、左辺の要素としてundefを使うというものです:
200139
201Another way is to use undef as an element on the left-hand-side:
140 ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
202141
203=end original
204
205もう一つのやりかたは、左辺の要素として undef を使うというものです:
206
207 ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
208
209=begin original
210
211You can also use a list slice to select only the elements that
212you need:
213
214=end original
215
216必要な要素だけを選択するために、リストスライスも使えます:
217
218 ($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5];
219
220142=head2 How do I temporarily block warnings?
221143
222144(一時的に警告をブロックするには?)
223145
224146=begin original
225147
226148If you are running Perl 5.6.0 or better, the C<use warnings> pragma
227149allows fine control of what warning are produced.
228150See L<perllexwarn> for more details.
229151
230152=end original
231153
232154Perl 5.6.0 以降を使っているなら、C<use warnings> プラグマで
233155どんな警告を生成するかをうまく制御できます。
234156詳細については L<perllexwarn> を参照してください。
235157
236 {
158 {
237159 no warnings; # temporarily turn off warnings
238160 $a = $b + $c; # I know these might be undef
239 }
161 }
240162
241163=begin original
242164
243Additionally, you can enable and disable categories of warnings.
244You turn off the categories you want to ignore and you can still
245get other categories of warnings. See L<perllexwarn> for the
246complete details, including the category names and hierarchy.
247
248=end original
249
250さらに、警告の分野毎に警告を有効または無効にできます。
251無視したいカテゴリを無効にしても、残りのカテゴリの警告は受けられます。
252カテゴリ名と階層を含む、完全な詳細については L<perllexwarn> を
253参照してください。
254
255 {
256 no warnings 'uninitialized';
257 $a = $b + $c;
258 }
259
260=begin original
261
262165If you have an older version of Perl, the C<$^W> variable (documented
263166in L<perlvar>) controls runtime warnings for a block:
264167
265168=end original
266169
267より古いバージョンの場合は、変数 C<$^W>(L<perlvar> に説明があります)は
170より古いバージョンの場合は、変数 C<$^W>(L<perlvar>に説明があります)は
268171実行時の警告のブロックを制御します:
269172
270=begin original
271
272 {
273 local $^W = 0; # temporarily turn off warnings
274 $a = $b + $c; # I know these might be undef
275 }
276
277=end original
278
279173 {
280174 local $^W = 0; # 一時的に警告をオフにする
281 $a = $b + $c; # これらが undef かもしれないことを知っている
175 $a = $b + $c; # これらがundefかもしれないことを知っている
282176 }
283177
284=begin original
178全ての句読点変数(punctuation variable)と同様、現時点ではC<$^W>に対して
179my() を使うことはできず、local()だけしか使えないということに注意してください。
285180
286Note that like all the punctuation variables, you cannot currently
287use my() on C<$^W>, only local().
288
289=end original
290
291全ての句読点変数(punctuation variable)と同様、現時点では C<$^W> に対して
292my() を使うことはできず、local() だけしか使えないということに
293注意してください。
294
295181=head2 What's an extension?
296182
297183(エクステンションてなんですか?)
298184
299=begin original
185エクステンションとは、Perlからコンパイル済みのCコードを呼び出すための方法です。
186エクステンションについて知るにはL<perlxstut>を読むのが良いでしょう。
300187
301An extension is a way of calling compiled C code from Perl. Reading
302L<perlxstut> is a good place to learn more about extensions.
303
304=end original
305
306エクステンションとは、Perl からコンパイル済みの C コードを呼び出すための
307方法です。
308エクステンションについて知るには L<perlxstut> を読むのが良いでしょう。
309
310188=head2 Why do Perl operators have different precedence than C operators?
311189
312190(なぜ Perl の演算子は C の演算子とは異なった優先順位を持っているのでしょうか?)
313191
314=begin original
192実際はそうではありません。Perlに持ち込まれたCの演算子はすべて、
315
316Actually, they don't. All C operators that Perl copies have the same
317precedence in Perl as they do in C. The problem is with operators that C
318doesn't have, especially functions that give a list context to everything
319on their right, eg. print, chmod, exec, and so on. Such functions are
320called "list operators" and appear as such in the precedence table in
321L<perlop>.
322
323=end original
324
325実際はそうではありません。Perl に持ち込まれたCの演算子はすべて、
326193C と Perl とで同じ優先順位を持っています。
327194問題は、C にはない演算子、特にその右辺に対してつねにリストコンテキストを
328195与える関数、例えば print、chmod、exec などです。
329そういった関数はリスト演算子と呼ばれ、
196そういった関数はリスト演算子と呼ばれ、
330197L<perlop> にある優先順位テーブルにあります。
331198
332=begin original
199ありがちな間違いは
333200
334A common mistake is to write:
201 unlink $file || die "snafu";
335202
336=end original
203のように書いてしまうことです。これは以下のように解釈されます:
337204
338ありがちな間違いは以下のようにのように書いてしまうことです:
205 unlink ($file || die "snafu");
339206
340 unlink $file || die "snafu";
207この問題を避けるためには、余計な括弧をつけるかより優先順位の低い C<or> 演算子を
208使うようにします:
341209
342=begin original
210 (unlink $file) || die "snafu";
211 unlink $file or die "snafu";
343212
344This gets interpreted as:
213“English”演算子(C<and>, C<or>, C<xor>, C<not>)は先に説明している
345
346=end original
347
348これは以下のように解釈されます:
349
350 unlink ($file || die "snafu");
351
352=begin original
353
354To avoid this problem, either put in extra parentheses or use the
355super low precedence C<or> operator:
356
357=end original
358
359この問題を避けるためには、余計な括弧をつけるかより優先順位の低い
360C<or> 演算子を使うようにします:
361
362 (unlink $file) || die "snafu";
363 unlink $file or die "snafu";
364
365=begin original
366
367The "English" operators (C<and>, C<or>, C<xor>, and C<not>)
368deliberately have precedence lower than that of list operators for
369just such situations as the one above.
370
371=end original
372
373"English" 演算子(C<and>, C<or>, C<xor>, C<not>) は先に説明している
374214同じ働きをするリスト演算子よりも低い優先順位を故意に持たされています。
375215
376=begin original
377
378Another operator with surprising precedence is exponentiation. It
379binds more tightly even than unary minus, making C<-2**2> produce a
380negative not a positive four. It is also right-associating, meaning
381that C<2**3**2> is two raised to the ninth power, not eight squared.
382
383=end original
384
385216もう一つの、びっくりするような優先順位を持っている演算子は
386217べき乗(exponentiation)です。
387これは単項のマイナスよりも強く結び付くので、C<-2**2> はプラス 4 ではなく、
218これは単項のマイナスよりも強く結び付くので、C<-2**2>はプラス4ではなく、
388マイナス 4 を生成します。
219マイナス4を生成します。この演算子は右結合するので、
389この演算子は右結合するので、C<2**3**2> 8 2 乗ではなく、
220C<2**3**2>は8の乗ではなく、2の九乗です。
3902 の 9 乗です。
391221
392222=begin original
393223
394224Although it has the same precedence as in C, Perl's C<?:> operator
395225produces an lvalue. This assigns $x to either $a or $b, depending
396226on the trueness of $maybe:
397227
398228=end original
399229
400C と同じ優先順位を持っているにも関らず、Perl では C<?:> 演算子は
230C と同じ優先順位を持っているにも関らず、PerlではC<?:>演算子は
401左辺値を作り出します。
231lvalue(代入可能な)を作り出します。以下の代入では、$maybe の値に応じて、
402以下の代入では、$maybe の値に応じて、$a か $b のいずれかに
232$a か $b のいずれかに$xの値を代入します:
403$x の値を代入します:
404233
405 ($maybe ? $a : $b) = $x;
234 ($maybe ? $a : $b) = $x;
406235
407236=head2 How do I declare/create a structure?
408237
409238(構造体を宣言したり生成するには?)
410239
411=begin original
240一般的には、構造体を“宣言”することはありません。単に(おそらくは無名の)
241ハッシュリファレンスを使うだけです。
242詳しくはL<perlref>と L<perldsc> を参照してください。例を挙げましょう:
412243
413In general, you don't "declare" a structure. Just use a (probably
244 $person = {}; # 新しい無名ハッシュ
414anonymous) hash reference. See L<perlref> and L<perldsc> for details.
245 $person->{AGE} = 24; # フィールド AGE に24を設定
415Here's an example:
246 $person->{NAME} = "Nat"; # フィールド NAME に "Nat"を設定
416247
417=end original
418
419一般的には、構造体を“宣言”することはありません。
420単に(おそらくは無名の)ハッシュリファレンスを使うだけです。
421詳しくは L<perlref>と L<perldsc> を参照してください。
422例を挙げましょう:
423
424 $person = {}; # new anonymous hash
425 $person->{AGE} = 24; # set field AGE to 24
426 $person->{NAME} = "Nat"; # set field NAME to "Nat"
427
428=begin original
429
430If you're looking for something a bit more rigorous, try L<perltoot>.
431
432=end original
433
434248もうちょっと正確ななにかを求めているのなら、
435249L<perltoot> に挑戦してみてください。
436250
437251=head2 How do I create a module?
438252
439253(モジュールを作成するには?)
440254
441=begin original
255モジュールとは同じ名前を持ったファイルに置かれているパッケージです。
256例えば、Hello::There というモジュールはHello/There.pmに置かれます。
257詳しいことは L<perlmod>を参照してください。L<Exporter>も助けになるでしょう。
258C か、C と Perl を混ぜたモジュールを作ろうとしているなら、
259L<perlxstut>で学んでおくべきでしょう。
442260
443(contributed by brian d foy)
261以下のものは、自分のモジュールを作ろうとしたときに使いたくなるような
262便利なテンプレートです。間違いなく名前を適切に変更してください。
444263
445=end original
264 package Some::Module; # Some/Module.pmを仮定
446265
447(brian d foy によって寄贈されました)
266 use strict;
267 use warnings;
448268
449=begin original
269 BEGIN {
270 use Exporter ();
271 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
450272
451L<perlmod>, L<perlmodlib>, L<perlmodstyle> explain modules
273 ## バージョンチェックのためのバージョンを設定。使うにはコメントを外す
452in all the gory details. L<perlnewmod> gives a brief
274 ## $VERSION = 1.00;
453overview of the process along with a couple of suggestions
454about style.
455275
456=end original
276 # RCS/VCSを使っているのなら次の行が好ましいでしょうが
277 # 二桁のバージョンに注意してください
278 $VERSION = do{my@r=q$Revision: 1.28 $=~/\d+/g;sprintf '%d.'.'%02d'x$#r,@r};
457279
458L<perlmod>, L<perlmodlib>, L<perlmodstyle> はモジュールに関する全ての
280 @ISA = qw(Exporter);
459不愉快な詳細について説明しています。
281 @EXPORT = qw(&func1 &func2 &func3);
460L<perlnewmod> にはこのプロセスに関する大まかな概要と、スタイルに関する
282 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
461いくつかの忠告があります。
462283
463=begin original
284 # exportするパッケージグローバルなものをここに置く。
285 # export可能な関数もここに置く。
286 @EXPORT_OK = qw($Var1 %Hashit);
287 }
288 our @EXPORT_OK;
464289
465If you need to include C code or C library interfaces in
290 # exported package globals go here
466your module, you'll need h2xs. h2xs will create the module
291 our $Var1;
467distribution structure and the initial interface files
292 our %Hashit;
468you'll need. L<perlxs> and L<perlxstut> explain the details.
469293
470=end original
294 # exportしないパッケージグローバルをここに
295 our @more;
296 our $stuff;
471297
472もしモジュールに C コードや C ライブラリインタフェ含めたなら、
298 # パッケジグロバル初期化する。最初にexportしてるものを。
473h2xs が必要です。
299 $Var1 = '';
474h2xs は必要になるモジュール配布構造と初期インターフェースファイルを
300 %Hashit = ();
475作成します。
476L<perlxs> と L<perlxstut> は詳細を説明しています。
477301
478=begin original
302 # それから他のもの(これらは$Some::Module::stuffとすればアクセスできます)を初期化する
303 $stuff = '';
304 @more = ();
479305
480If you don't need to use C code, other tools such as
306 # ファイルスコープを持った全てのlecicalは
481ExtUtils::ModuleMaker and Module::Starter, can help you
307 # 関数がそれ使うよりも前に生成しておかねばならない
482create a skeleton module distribution.
483308
484=end original
309 # ファイルプライベートなlexicalsはここに
310 my $priv_var = '';
311 my %secret_hash = ();
485312
486Cドを使う必要がいのならExtUtils::ModuleMaker や
313 # これはクロージャーとしてファイルプライベ関数で
487Module::Starter といったツール、モジュール配布の骨格を作
314 # &$priv_funcで呼び出しでき。これはプロトタイプ作れない。
488助けてくれます。
315 my $priv_func = sub {
316 # 内容をここに
317 };
489318
490=begin original
319 # exportするしないに関らず、全ての関数を作成する。
320 # {}スタブを適当に埋めることを忘れないように
321 sub func1 {} # プロトタイプなし
322 sub func2() {} # void のプロトタイプ
323 sub func3($$) {} # 二つのスカラーを取るプロトタイプ
491324
492You may also want to see Sam Tregar's "Writing Perl Modules
325 # これはexportされないが、それでも呼び出しは可能!
493for CPAN" ( http://apress.com/book/bookDisplay.html?bID=14 )
326 sub func4(\%) {} # 一つのハッシュリファレンスを取るプロトタイプ
494which is the best hands-on guide to creating module
495distributions.
496327
497=end original
328 END { } # モジュールの後始末コードをここに (グローバルデストラクター)
498329
499モジュール配布を作成するための最良の実践型ガイドである、Sam Tregar による
330 1; # モジュールはtureを返さなければならない
500"Writing Perl Modules for CPAN"
501( http://apress.com/book/bookDisplay.html?bID=14 ) を見るのもよいでしょう。
502331
503=head2 How do I adopt or take over a module already on CPAN?
332h2xsというプログラムはあなたのために、重要なもの全てのためのスタブを作成します。
504333
505(すでに CPAN にあるモジュールを引き継ぐには?)
334 % h2xs -XA -n My::Module
506335
507=begin original
508
509(contributed by brian d foy)
510
511=end original
512
513(brian d foy によって寄贈されました)
514
515=begin original
516
517The easiest way to take over a module is to have the current
518module maintainer either make you a co-maintainer or transfer
519the module to you.
520
521=end original
522
523モジュールを引き継ぐのに一番簡単な方法は、現在のモジュールのメンテナに
524連絡して、共同メンテナにしてもらうか、モジュールを引き渡してもらう
525ことです。
526
527=begin original
528
529If you can't reach the author for some reason (e.g. email bounces),
530the PAUSE admins at modules@perl.org can help. The PAUSE admins
531treat each case individually.
532
533=end original
534
535もし何らかの理由(メールが返ってきたなど)で作者と連絡が取れない場合、
536PAUSE 管理者である modules@perl.org が助けになるかもしれません。
537PAUSE 管理者はそれぞれの場合を個別に扱います。
538
539=over 4
540
541=item *
542
543=begin original
544
545Get a login for the Perl Authors Upload Server (PAUSE) if you don't
546already have one: http://pause.perl.org
547
548=end original
549
550まだ持っていないなら、the Perl Authors Upload Server (PAUSE) のアカウントを
551取ります: http://pause.perl.org
552
553=item *
554
555=begin original
556
557Write to modules@perl.org explaining what you did to contact the
558current maintainer. The PAUSE admins will also try to reach the
559maintainer.
560
561=end original
562
563現在のメンテナに連絡するためにしたことの説明を modules@perl.org に書きます。
564PAUSE 管理者もメンテナに連絡を試みます。
565
566=item *
567
568=begin original
569
570Post a public message in a heavily trafficked site announcing your
571intention to take over the module.
572
573=end original
574
575モジュールを引き継ぎたいという意思を表明するために、トラフィックの多い
576サイトに公的なメッセージを投稿します。
577
578=item *
579
580=begin original
581
582Wait a bit. The PAUSE admins don't want to act too quickly in case
583the current maintainer is on holiday. If there's no response to
584private communication or the public post, a PAUSE admin can transfer
585it to you.
586
587=end original
588
589しばらく待ちます。
590PAUSE 管理者は、現在のメンテナが休暇中の場合に、あまりに性急に行動したいとは
591思いません。
592もし私的な通信や公的な投稿に反応がない場合、PAUSE 管理者はモジュールを
593あなたに移行できます。
594
595=back
596
597336=head2 How do I create a class?
598X<class, creation> X<package>
599337
600338(クラスを作るには?)
601339
602=begin original
340クラスとオブジェクトについての入門は L<perltoot>を参照してください。
341同様に、L<perlobj> と L<perlbot>も参照してください。
603342
604(contributed by brian d foy)
605
606=end original
607
608(brian d foy によって寄贈されました)
609
610=begin original
611
612In Perl, a class is just a package, and methods are just subroutines.
613Perl doesn't get more formal than that and lets you set up the package
614just the way that you like it (that is, it doesn't set up anything for
615you).
616
617=end original
618
619Perl では、クラスは単なるパッケージで、メソッドは単なるサブルーチンです。
620Perl はそれ以上に形式的なことはしませんし、あなたの好きな方法でパッケージを
621設定できるようにします (つまり、Perl はあなたのために何の設定もしません)。
622
623=begin original
624
625The Perl documentation has several tutorials that cover class
626creation, including L<perlboot> (Barnyard Object Oriented Tutorial),
627L<perltoot> (Tom's Object Oriented Tutorial), L<perlbot> (Bag o'
628Object Tricks), and L<perlobj>.
629
630=end original
631
632Perl の文書には、
633L<perlboot> (Barnyard Object Oriented Tutorial),
634L<perltoot> (Tom's Object Oriented Tutorial), L<perlbot> (Bag o'
635Object Tricks), L<perlobj> といった、クラス生成に対応する
636いくつかのチュートリアルがあります。
637
638343=head2 How can I tell if a variable is tainted?
639344
640(変数が汚染されているかどうかを確かめるには?)
345(変数が汚染されているかどうかをどうやれば確かめられますか?)
641346
642=begin original
347L<perlsec/"Laundering and Detecting Tainted Data">を参照してください。
348以下に例を示します(これはkill()がシグナルを送る何のプロセスも
349与えられていないのでなんのシステムコールも使いません):
643350
644You can use the tainted() function of the Scalar::Util module, available
351 sub is_tainted {
645from CPAN (or included with Perl since release 5.8.0).
352 return ! eval { join('',@_), kill 0; 1; };
646See also L<perlsec/"Laundering and Detecting Tainted Data">.
353 }
647354
648=end original
355しかしこれは C<-w>クリーンではありません。汚染検査を C<-w>クリーンにする
356方法はありません。
357これは汚染された可能性のあるデータ全てを浄化(untaint)すべき
358ヒントであると受け取ってください。
649359
650CPAN にある (リリース 5.8.0 からは Perl に含まれている) Scalar::Util
651モジュールの tainted() 関数が使えます。
652L<perlsec/"Laundering and Detecting Tainted Data"> も参照してください。
653
654360=head2 What's a closure?
655361
656(クロージャ(closure)ってなんですか?)
362(クロージャ(closure)ってなんですか?)
657363
658364=begin original
659365
660366Closures are documented in L<perlref>.
661367
662368=end original
663369
664クロージャは L<perlref> に説明があります。
370クロージャはL<perlref>に説明があります。
665371
666=begin original
372B<クロージャー>は、きちんとした定義を持ったコンピューター科学の用語ですが
667
668I<Closure> is a computer science term with a precise but
669hard-to-explain meaning. Usually, closures are implemented in Perl as
670anonymous subroutines with lasting references to lexical variables
671outside their own scopes. These lexicals magically refer to the
672variables that were around when the subroutine was defined (deep
673binding).
674
675=end original
676
677B<クロージャ> は、きちんとした定義を持ったコンピュータ科学の用語ですが
678373その意味を説明するのはとても難しいのです。
679クロージャは Perl では、そのスコープの外側でもレキシカル変数に対する
374クロージャは Perl では、そのスコープの外側でもレキシカル変数に対する
680375リファレンスを保持しつづける無名サブルーチンとして実装されています。
681376これらのレキシカルは、サブルーチンが定義されたときの変数に対して、
682377魔法のような参照(magically refer)を行います(深い束縛、deep binding)。
683378
684=begin original
379クロージャーは、Perlができるような関数の戻り値として関数それ自身を返す関数を
380持つことができるプログラミング言語で意味があります。
686Closures are most often used in programming languages where you can
381一部の言語では、無名関数を提供しているけれども適切なクロージャーを提供する
687have the return value of a function be itself a function, as you can
688in Perl. Note that some languages provide anonymous functions but are
689not capable of providing proper closures: the Python language, for
690example. For more information on closures, check out any textbook on
691functional programming. Scheme is a language that not only supports
692but encourages closures.
693
694=end original
695
696クロージャは、Perl ができるような関数の戻り値として関数それ自身を返す関数を
697持つことができるプログラミング言語でもっともよく使われます。
698一部の言語では、無名関数を提供しているけれども適切なクロージャを提供する
699382能力はないということに注意してください。
700383たとえば Python がそうです。
701クロージャに関するより詳しいことは、関数言語に関するなんらかの教科書を
384クロージャに関するより詳しいことは、関数言語に関するなんらかの教科書を
702385みてください。
703Scheme はクロージャをサポートするだけでなく、それを推奨している言語です。
386Scheme はクロージャをサポートするだけでなく、それを推奨している言語です。
704387
705=begin original
388以下は、古典的な関数を生成する関数です:
706389
707Here's a classic non-closure function-generating function:
390 sub add_function_generator {
391 return sub { shift + shift };
392 }
708393
709=end original
394 $add_sub = add_function_generator();
395 $sum = $add_sub->(4,5); # $sum はここで 9 となる
710396
711以下は、古典的な、クロージャない関数を生成す関数す:
397クロージャ、後で埋めことのきるカスタマイズ可能な幾つかのスロットを持つ
398B<関数テンプレート>のように働きます。
713 sub add_function_generator {
714 return sub { shift() + shift() };
715 }
716
717 $add_sub = add_function_generator();
718 $sum = $add_sub->(4,5); # $sum is 9 now.
719
720=begin original
721
722The anonymous subroutine returned by add_function_generator() isn't
723technically a closure because it refers to no lexicals outside its own
724scope. Using a closure gives you a I<function template> with some
725customization slots left out to be filled later.
726
727=end original
728
729399add_function_generator() が返した無名サブルーチンは技術的には
730クロージャではありません。
400クロージャではありません。
731401なぜなら、あれはスコープの外側で参照するようなレキシカルがないからです。
732クロージャを使うことによって、後で埋めることのできるカスタマイズ可能な
733幾つかのスロットを持つ B<関数テンプレート> のように働きます。
734402
735=begin original
403それとは対照的に、次の関数 make_adder()では、関数自身のスコープの外側で
736
737Contrast this with the following make_adder() function, in which the
738returned anonymous function contains a reference to a lexical variable
739outside the scope of that function itself. Such a reference requires
740that Perl return a proper closure, thus locking in for all time the
741value that the lexical had when the function was created.
742
743=end original
744
745それとは対照的に、次の関数 make_adder() では、関数自身のスコープの外側で
746404レキシカル変数に対するリファレンスを持つ無名関数を返します。
747そのようなリファレンスは Perl が適切なクロージャを返すように要求するので、
405そのようなリファレンスは Perl が適切なクロージャを返すように要求するので、
748406その変数を参照するときはいつでも関数が生成されたときの
749407レキシカルが参照されます。
750408
751 sub make_adder {
409 sub make_adder {
752 my $addpiece = shift;
410 my $addpiece = shift;
753 return sub { shift() + $addpiece };
411 return sub { shift + $addpiece };
754 }
412 }
755413
756 $f1 = make_adder(20);
414 $f1 = make_adder(20);
757 $f2 = make_adder(555);
415 $f2 = make_adder(555);
758416
759=begin original
417これで、C<&$f1($n)>は それに渡した $nに対して常に20を加え、
418C<&$f2($n)>は渡された $nに常に555を加えます。
419クロージャーの中にある $addpieceが仕事をしています。
760420
761Now C<&$f1($n)> is always 20 plus whatever $n you pass in, whereas
762C<&$f2($n)> is always 555 plus whatever $n you pass in. The $addpiece
763in the closure sticks around.
764421
765=end original
422クロージャーは、それほど難しくない状況でよく使われます。たとえば、
423関数にちょっとしたコードを押しこみたいときがそうです:
766424
767これで、C<&$f1($n)> それに渡した $n に対して常に 20 を加え、
425 my $line;
768C<&$f2($n)> は渡された $n に常に 555 を加えます。
426 timeout( 30, sub { $line = <STDIN> } );
769クロージャの中にある $addpiece が仕事をしています。
770427
771428=begin original
772429
773Closures are often used for less esoteric purposes. For example, when
774you want to pass in a bit of code into a function:
775
776=end original
777
778クロージャは、それほど難しくない状況でよく使われます。
779たとえば、関数にちょっとしたコードを押しこみたいときがそうです:
780
781 my $line;
782 timeout( 30, sub { $line = <STDIN> } );
783
784=begin original
785
786430If the code to execute had been passed in as a string,
787431C<< '$line = <STDIN>' >>, there would have been no way for the
788432hypothetical timeout() function to access the lexical variable
789433$line back in its caller's scope.
790434
791435=end original
792436
793437もし実行すべきコードが文字列として渡されていたのであれば、
794C<< '$line = <STDIN>' >> としているところは、仮想的な timeout() 関数が
438C<< '$line = <STDIN>' >> としているところは、仮想的な timeout()
795アクセスするレキシカル変数 $line を呼び出し元のスコープのものに戻す
439関数が アクセスする lexical変数 $lineを呼び出し元のスコープのものに戻す
796440手段がなくなってしまいます。
797441
798=begin original
799
800Another use for a closure is to make a variable I<private> to a
801named subroutine, e.g. a counter that gets initialized at creation
802time of the sub and can only be modified from within the sub.
803This is sometimes used with a BEGIN block in package files to make
804sure a variable doesn't get meddled with during the lifetime of the
805package:
806
807=end original
808
809もう一つのクロージャの使用法は、ある変数を名前つきサブルーチンで
810I<プライベート> にすることです; 例えば、サブルーチンの作成時に初期化され、
811サブルーチン内でのみ変更可能なカウンタです。
812これは、パッケージの生存期間中に変数が干渉されることがないように、とき毒
813パッケージファイルの BEGIN ブロックで使われます:
814
815 BEGIN {
816 my $id = 0;
817 sub next_id { ++$id }
818 }
819
820=begin original
821
822This is discussed in more detail in L<perlsub>; see the entry on
823I<Persistent Private Variables>.
824
825=end original
826
827これは L<perlsub> でより詳しく議論されています;
828I<Persistent Private Variables> のエントリを参照してください。
829
830442=head2 What is variable suicide and how can I prevent it?
831443
832444(変数の自殺(variable suicide)って何で、それをどうすれば防げますか?)
833445
834446=begin original
835447
836This problem was fixed in perl 5.004_05, so preventing it means upgrading
448Variable suicide is when you (temporarily or permanently) lose the
837your version of perl. ;)
449value of a variable. It is caused by scoping through my() and local()
450interacting with either closures or aliased foreach() iterator
451variables and subroutine arguments. It used to be easy to
452inadvertently lose a variable's value this way, but now it's much
453harder. Take this code:
838454
839455=end original
840456
841問題 5.004_05 で修正されたので防ぐためは perl
457変数自殺とは、(一時的しろ、恒久的にしろ)変数の値失ったときのことを指します。
842ージョンアップます :)
458これは、クロージャー、もくは別名つけされた foreach イテレーター変数や
459サブルーチンの引数と相互作用しているmy()やlocal()を通したスコープによって
460引き起こされます。
461以前はこのやり方で変数の値をうっかりとなくしてしまうように使われがちでしたが、
462現在は非常に難しくなっています。以下のコードを考えてみましょう:
843463
844=begin original
464 my $f = "foo";
465 sub T {
466 while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" }
467 }
468 T;
469 print "Finally $f\n";
845470
846Variable suicide is when you (temporarily or permanently) lose the value
847of a variable. It is caused by scoping through my() and local()
848interacting with either closures or aliased foreach() iterator variables
849and subroutine arguments. It used to be easy to inadvertently lose a
850variable's value this way, but now it's much harder. Take this code:
851
852=end original
853
854変数の自殺とは、(一時的にしろ、恒久的にしろ)変数の値を失ったときのことを
855指します。
856これは、クロージャ、もしくは別名つけされた foreach イテレータ変数や
857サブルーチンの引数と相互作用している my() や local() を通した
858スコープによって引き起こされます。
859以前はこのやり方で変数の値をうっかりとなくしてしまうように
860使われがちでしたが、現在は非常に難しくなっています。
861以下のコードを考えてみましょう:
862
863 my $f = 'foo';
864 sub T {
865 while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" }
866 }
867
868 T;
869 print "Finally $f\n";
870
871471=begin original
872472
873If you are experiencing variable suicide, that C<my $f> in the subroutine
874doesn't pick up a fresh copy of the C<$f> whose value is <foo>. The output
875shows that inside the subroutine the value of C<$f> leaks through when it
876shouldn't, as in this output:
877
878=end original
879
880もし変数の自殺に遭遇したら、サブルーチン内の C<my $f> は、値が C<foo> である
881C<$f> の最新のコピーをではありません。
882この出力は、漏れてはいけないサブルーチン内の C<$f> の値が漏れていることを
883示し、以下のようになります:
884
885 foobar
886 foobarbar
887 foobarbarbar
888 Finally foo
889
890=begin original
891
892473The $f that has "bar" added to it three times should be a new C<$f>
893C<my $f> should create a new lexical variable each time through the loop.
474(C<my $f> should create a new local variable each time through the loop).
894The expected output is:
475It isn't, however. This was a bug, now fixed in the latest releases
476(tested against 5.004_05, 5.005_03, and 5.005_56).
895477
896478=end original
897479
898"bar" を保持している $f は三回 new C<$f> されるべきものです (C<my $f> は、
480"bar" を保持している$fは三回 new C<$f>されるべきものです (C<my $f>は、
899ループが通る度に新たなレキシカル変数を生成すべきなのです)。
481ループが通る度に新たなローカル変数を生成すべきなのです)。
900予想さる出力以下のものす:
482しかしそうではありません。これはバグした。
483最新のリリース(5.004_05, 5.005_03, and 5.005_56)では修正されています。
901484
902 foobar
903 foobar
904 foobar
905 Finally foo
906
907485=head2 How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?
908486
909({関数, ファイルハンドル, 配列, ハッシュ, メソッド, 正規表現} を渡したり返したりるに?)
487({関数, ファイルハンドル, 配列, ハッシュ, メソッド, 正規表現} を渡したり返す
488どうすればできますか?)
910489
490正規表現を除いて、これらのオブジェクトのリファレンスを渡す必要があります。
491L<perlsub/"Pass by Reference">にある関連した質問と、
492L<perlref>にあるリファレンスに関する情報を参照してください。
493
911494=begin original
912495
913You need to pass references to these objects. See L<perlsub/"Pass by
496See ``Passing Regexes'', below, for information on passing regular
914Reference"> for this particular question, and L<perlref> for
497expressions.
915information on references.
916498
917499=end original
918500
919これらのオブジェクトのリファレンスを渡す必要があります。
501正規表現を渡すための情報については、下記の``Passing Regexes''を
920L<perlsub/"Pass by Reference"> にある関連た質問と、
502参照て下さい。
921L<perlref> にあるリファレンスに関する情報を参照してください。
922503
923504=over 4
924505
925506=item Passing Variables and Functions
926507
927508(変数や関数を渡す)
928509
929=begin original
930
931Regular variables and functions are quite easy to pass: just pass in a
932reference to an existing or anonymous variable or function:
933
934=end original
935
936510普通の変数や関数はとても簡単に渡せます: 既に存在している変数や関数に対する
937511リファレンスか、無名変数や無名関数に対するリファレンスを渡せばよいのです。
938512
939 func( \$some_scalar );
513 func( \$some_scalar );
940514
941 func( \@some_array );
515 func( \@some_array );
942 func( [ 1 .. 10 ] );
516 func( [ 1 .. 10 ] );
943517
944 func( \%some_hash );
518 func( \%some_hash );
945 func( { this => 10, that => 20 } );
519 func( { this => 10, that => 20 } );
946520
947 func( \&some_func );
521 func( \&some_func );
948 func( sub { $_[0] ** $_[1] } );
522 func( sub { $_[0] ** $_[1] } );
949523
950=item Passing Filehandles
524=item ファイルハンドルを渡す
951525
952526=begin original
953527
954As of Perl 5.6, you can represent filehandles with scalar variables
528To pass filehandles to subroutines, use the C<*FH> or C<\*FH> notations.
955which you treat as any other scalar.
956
957=end original
958
959Perl 5.6 から、他のスカラと同様にファイルハンドルもスカラ変数で扱えます。
960
961 open my $fh, $filename or die "Cannot open $filename! $!";
962 func( $fh );
963
964 sub func {
965 my $passed_fh = shift;
966
967 my $line = <$passed_fh>;
968 }
969
970=begin original
971
972Before Perl 5.6, you had to use the C<*FH> or C<\*FH> notations.
973529These are "typeglobs"--see L<perldata/"Typeglobs and Filehandles">
974530and especially L<perlsub/"Pass by Reference"> for more information.
975531
976532=end original
977533
978Perl 5.6 より前では、C<*FH> C<\*FH> といった記法を使う必要があります。
534サブルーチンにファイルハンドルを渡すには、C<*FH>やC<\*FH>といった記法を使ます。
979535これらは“型グロブ”(typeglob)です。
980L<perldata/"Typeglobs and Filehandles">) L<perlsub/"Pass by Reference">
536L<perldata/"Typeglobs and Filehandles">)とL<perlsub/"Pass by Reference">に
981537詳しい説明があります。
982538
983=item Passing Regexes
539以下はその抜粋です:
984540
985(正規表現を渡す)
541ファイルハンドルを渡すのであれば
542*STDOUTのような裸の型グロブを使うこともできますが、
543型グロブのリファレンスを渡す方がもっと良いです。
544なぜなら、そうしておけばC<use strict 'refs'>の状態でも正しく働くからです。
545例を挙げましょう:
986546
987=begin original
547 splutter(\*STDOUT);
548 sub splutter {
549 my $fh = shift;
550 print $fh "her um well a hmmm\n";
551 }
988552
989Here's an example of how to pass in a string and a regular expression
553 $rec = get_rec(\*STDIN);
990for it to match against. You construct the pattern with the C<qr//>
554 sub get_rec {
991operator:
555 my $fh = shift;
556 return scalar <$fh>;
557 }
992558
993=end original
559もし新しいファイルハンドルを生成しようと考えているのなら、
560以下のようにすればできます:
994561
995以下の例は、文字列とマッチングする正規表現を渡す方法です。
562 sub openit {
996パターンを C<qr//> 演算子で構築します:
563 my $path = shift;
564 local *FH;
565 return open (FH, $path) ? *FH : undef;
566 }
567 $fh = openit('< /etc/motd');
568 print <$fh>;
997569
998 sub compare($$) {
570=item 正規表現を渡す
999 my ($val1, $regex) = @_;
1000 my $retval = $val1 =~ /$regex/;
1001 return $retval;
1002 }
1003 $match = compare("old McDonald", qr/d.*D/i);
1004571
1005=item Passing Methods
1006
1007(メソッドを渡す)
1008
1009572=begin original
1010573
1011To pass an object method into a subroutine, you can do this:
574To pass regexes around, you'll need to be using a release of Perl
575sufficiently recent as to support the C<qr//> construct, pass around
576strings and use an exception-trapping eval, or else be very, very clever.
1012577
1013578=end original
1014579
1015サブルーチンにオブジェクトメソッドを渡すには、以下にできます:
580正規表現を渡すには、C<qr//> 構造が利用可能な最近 Perl を使か、
581文字列を渡したあとで exception-trapping evalを使うか、
582さもなければとてもとても賢明でなければなりません。
1016583
1017 call_a_lot(10, $some_obj, "methname")
1018 sub call_a_lot {
1019 my ($count, $widget, $trick) = @_;
1020 for (my $i = 0; $i < $count; $i++) {
1021 $widget->$trick();
1022 }
1023 }
1024
1025584=begin original
1026585
1027Or, you can use a closure to bundle up the object, its
586Here's an example of how to pass in a string to be regex compared
1028method call, and arguments:
587using C<qr//>:
1029588
1030589=end original
1031590
1032オブジェクトとそメソッド呼び出しと引数とめるために
591以下例は、c<qr//>使って正規表現して比較すべき文字列を渡す方法の例です:
1033クロージャを使うこともできます:
1034592
1035 my $whatnot = sub { $some_obj->obfuscate(@args) };
593 sub compare($$) {
1036 func($whatnot);
594 my ($val1, $regex) = @_;
1037 sub func {
595 my $retval = $val1 =~ /$regex/;
1038 my $code = shift;
596 return $retval;
1039 &$code();
597 }
1040 }
598 $match = compare("old McDonald", qr/d.*D/i);
1041599
1042600=begin original
1043601
1044You could also investigate the can() method in the UNIVERSAL class
602Notice how C<qr//> allows flags at the end. That pattern was compiled
1045(part of the standard perl distribution).
603at compile time, although it was executed later. The nifty C<qr//>
604notation wasn't introduced until the 5.005 release. Before that, you
605had to approach this problem much less intuitively. For example, here
606it is again if you don't have C<qr//>:
1046607
1047608=end original
1048609
1049UNIVERSAL クラス can() メソッドを試すことできます
610C<qr//> の末尾付けることできるフラグに注意してください。
1050(れは標準 perl 配布キットの部です)。
611このパターンは度だけコンパイル時にコンパイルされ、
612実行時にはコンパイルされません。
613このしゃれた C<qr//> 記法は 5.005 リリースで初めて提供されました。
614それまでは、この問題に対して遥かに直感的でない手法をとらなければなりませんでした。
615例えば、先ほどのコードを C<qr//> なしで書くと:
1051616
1052=back
617 sub compare($$) {
618 my ($val1, $regex) = @_;
619 my $retval = eval { $val1 =~ /$regex/ };
620 die if $@;
621 return $retval;
622 }
1053623
1054=head2 How do I create a static variable?
624 $match = compare("old McDonald", q/($?i)d.*D/);
1055625
1056(静的変数を作るには?)
626決して以下のようしていけません:
1057627
1058=begin original
628 return eval "\$val =~ /$regex/"; # 間違い
1059629
1060(contributed by brian d foy)
630あるいは、誰かがevalの二重展開とダブルクォートで括られた文字列のために、
631正規表現に妙なシェルエスケープを押し込むかもしれません。
632例を挙げましょう:
1061633
1062=end original
634 $pattern_of_evil = 'danger ${ system("rm -rf * &") } danger';
1063635
1064(brian d foy によって寄贈されました)
636 eval "\$string =~ /$pattern_of_evil/";
1065637
1066638=begin original
1067639
1068In Perl 5.10, declare the variable with C<state>. The C<state>
640Those preferring to be very, very clever might see the O'Reilly book,
1069declaration creates the lexical variable that persists between calls
641I<Mastering Regular Expressions>, by Jeffrey Friedl. Page 273's
1070to the subroutine:
642Build_MatchMany_Function() is particularly interesting. A complete
643citation of this book is given in L<perlfaq2>.
1071644
1072645=end original
1073646
1074Perl 5.10 では、C<state> で変数を宣言します。
647これらのことに関してとてもとても賢明になるには、
1075C<state> 宣言は、サブルーチンの呼び出しの間で永続するレキシカル変数
648Jeffrey Friedl による O'Reillyの本 I<Mastering Regular Expressions>を
1076作成ます:
649読むことでょう。
650特に 273ページにある Build_MatchMany_Function()は興味深いものです。
651この本に関する完全な情報は L<perlfaq2>にあります。
1077652
1078 sub counter { state $count = 1; $counter++ }
653=item Passing Methods
1079654
1080=begin original
655(メソッドを渡す)
1081656
1082You can fake a static variable by using a lexical variable which goes
657サブルーチンにオブジェクトメソッドを渡すには、以下のようにできます:
1083out of scope. In this example, you define the subroutine C<counter>, and
1084it uses the lexical variable C<$count>. Since you wrap this in a BEGIN
1085block, C<$count> is defined at compile-time, but also goes out of
1086scope at the end of the BEGIN block. The BEGIN block also ensures that
1087the subroutine and the value it uses is defined at compile-time so the
1088subroutine is ready to use just like any other subroutine, and you can
1089put this code in the same place as other subroutines in the program
1090text (i.e. at the end of the code, typically). The subroutine
1091C<counter> still has a reference to the data, and is the only way you
1092can access the value (and each time you do, you increment the value).
1093The data in chunk of memory defined by C<$count> is private to
1094C<counter>.
1095658
1096=end original
659 call_a_lot(10, $some_obj, "methname")
660 sub call_a_lot {
661 my ($count, $widget, $trick) = @_;
662 for (my $i = 0; $i < $count; $i++) {
663 $widget->$trick();
664 }
665 }
1097666
1098スコープ外でレキシカル変数を使うこでスタティク変数を
667オブジェクトそのメソド呼び出しと引まとめるために
1099でっち上げることできます
668クロージャーを使うことできます:
1100この例では、サブルーチン C<counter> を定義し、そこでレキシカル変数
1101C<$count> を使います。
1102これを BEGIN ブロックで囲っているので、C<$count> はコンパイル時に
1103定義されますが、BEGIN ブロックの終わりでスコープから外れます。
1104BEGIN ブロックはまた、サブルーチンとそこで使われている値はコンパイル時に
1105定義されるので、このサブルーチンはその他のどのサブルーチンからも
1106使える準備が出来ていて、このコードをプログラムテキスト中の他のサブルーチンと
1107同様に同じ場所(典型的には、コードの最後)にこのコードを置けることを保証します。
1108サブルーチン C<counter> は未だにデータへのリファレンスを持っていて、
1109これが値にアクセスできる唯一の方法です(そしてそうする度に、値が
1110インクリメントされます)。
1111C<$count> で定義されたメモリの塊にあるデータは C<counter> に
1112プライベートです。
1113669
1114 BEGIN {
670 my $whatnot = sub { $some_obj->obfuscate(@args) };
1115 my $count = 1;
671 func($whatnot);
1116 sub counter { $count++ }
672 sub func {
1117 }
673 my $code = shift;
674 &$code();
675 }
1118676
1119 my $start = counter();
677UNIVERSALクラスにあるcan()メソッドを試すこともできます
678(これは標準の perl 配布キットの一部です)。
1120679
1121 .... # code that calls counter();
680=back
1122681
1123 my $end = counter();
682=head2 How do I create a static variable?
1124683
684(静的変数(static variable)を作るには?)
685
686Perlにおけるほとんどの事柄と同様、TMTOWTDI(やり方はいくつもあります)です。
687他の言語における“静的変数”は、Perlでは関数にプライベート
688(その変数が宣言されたある単一の関数でのみ可視で、
689関数の呼び出しの間その値を保っている)な変数かファイルに
690プライベート(変数が宣言されたファイルにある関数からのみ可視)な変数の
691いずれかになります。
692
1125693=begin original
1126694
1127In the previous example, you created a function-private variable
695Here's code to implement a function-private variable:
1128because only one function remembered its reference. You could define
1129multiple functions while the variable is in scope, and each function
1130can share the "private" variable. It's not really "static" because you
1131can access it outside the function while the lexical variable is in
1132scope, and even create references to it. In this example,
1133C<increment_count> and C<return_count> share the variable. One
1134function adds to the value and the other simply returns the value.
1135They can both access C<$count>, and since it has gone out of scope,
1136there is no other way to access it.
1137696
1138697=end original
1139698
1140前述の例は、関数プライベートな変数を作っていま;
699以下の例は、関数プライベートな変数を実装るものです:
1141ただ一つの関数だけがこのリファレンスを覚えているからです。
1142変数がスコープ内にある間に複数の関数を定義でき、各関数は「プライベート」
1143変数を共有できます。
1144レキシカル変数がスコープ内ではあるけれども関数の外側から変数にアクセスでき、
1145それに対するリファレンスすら作成できるため、これは実際には
1146「静的」変数ではありません。
1147この例では、C<increment_count> と C<return_count> は変数を共有しています。
1148片方の関数が値を加え、もう片方は単に値を返します。
1149これらは両方とも C<$count> にアクセスでき、スコープ外から離れるため、
1150これにアクセスするその他の方法はありません。
1151700
1152 BEGIN {
701 BEGIN {
1153 my $count = 1;
702 my $counter = 42;
1154 sub increment_count { $count++ }
703 sub prev_counter { return --$counter }
1155 sub return_count { $count }
704 sub next_counter { return $counter++ }
1156 }
705 }
1157706
707これで、prev_counter() と next_counter() はコンパイル時に初期化された
708$counter というプライベート変数を共有します。
709
1158710=begin original
1159711
1160To declare a file-private variable, you still use a lexical variable.
712To declare a file-private variable, you'll still use a my(), putting
1161A file is also a scope, so a lexical variable defined in the file
713the declaration at the outer scope level at the top of the file.
1162cannot be seen from any other file.
714Assume this is in file Pax.pm:
1163715
1164716=end original
1165717
1166ファイルプライベートな変数を宣言するには、やはりレキシカル変数が使えます。
718ファイルプライベートな変数を宣言するにはmy()を使う必要があり、
1167ファイルスコープとなるので、あるファイルで定義されたキシカ変数は
719ファイルの先頭で outer スコープレに宣言を置きます。
1168他のファイルからは見えせん。
720以下コードが Pax.pm というファイルにあったと仮定しす:
1169721
722 package Pax;
723 my $started = scalar(localtime(time()));
724
725 sub begun { return $started }
726
1170727=begin original
1171728
1172See L<perlsub/"Persistent Private Variables"> for more information.
729When C<use Pax> or C<require Pax> loads this module, the variable will
1173The discussion of closures in L<perlref> may help you even though we
730be initialized. It won't get garbage-collected the way most variables
1174did not use anonymous subroutines in this answer. See
731going out of scope do, because the begun() function cares about it,
1175L<perlsub/"Persistent Private Variables"> for details.
732but no one else can get it. It is not called $Pax::started because
733its scope is unrelated to the package. It's scoped to the file. You
734could conceivably have several packages in that same file all
735accessing the same private variable, but another file with the same
736package couldn't get to it.
1176737
1177738=end original
1178739
1179さらなる情報については L<perlsub/"Persistent Private Variables">
740C<use Pax> か C<require Pax> によってこのモジュールがロードされたとき、
1180参照してくだ
741この変数は初期化れます
1181L<perlref> でのクロージャに関する議論は、この答えに無名サブルチンは
742この変数ほとんどの変数がスコプから外れたときのように
1182使っていないですが、助けになるかもしれません。
743ガーベッジコレクトさることはありません。
1183詳細については L<perlsub/"Persistent Private Variables"> 参照しくださ
744なぜなら、begun()関数はこの変数使っていて、他の誰もこの変数を
745手に入れることはできないからです。
746これは $Pax::started と呼び出すこともできません。
747なぜなら、そのスコープはパッケージには関係ないものだからです。
748それはファイルスコープなのです。
749同じファイル中で同じプライベート変数をアクセスできるけれども、
750同じパッケージの他のファイルが変数にアクセスすることはできないような、
751幾つかのパッケージを持つことができると想像できるでしょう
1184752
753詳しくは L<perlsub/"Perstent Private Variables"> を参照してください。
754
1185755=head2 What's the difference between dynamic and lexical (static) scoping? Between local() and my()?
1186756
1187(動的スコープとレキシカル(または静的)スコープとの間の違いは? local() my() との違い?)
757(動的スコープ(dynamic scoping)とレキシカルスコープ(lexical scoping, もしく
758static scoping)との間の違いは何ですか? local()とmy()との違いは?)
1188759
1189760=begin original
1190761
1191762C<local($x)> saves away the old value of the global variable C<$x>
1192763and assigns a new value for the duration of the subroutine I<which is
1193764visible in other functions called from that subroutine>. This is done
1194765at run-time, so is called dynamic scoping. local() always affects global
1195766variables, also called package variables or dynamic variables.
1196767
1197768=end original
1198769
1199C<local($x)> は、グローバル変数 C<$x> 古い値を保存して、
770C<local($x)> は、C<$x>のグローバルな値を保存して、サブルーチンの
1200I<そのサブルーチンから呼び出された関数から参照できる> サブルーチンの
1201771存在する間の新たな値を代入します。
1202コンパイル時ではなく、実行時に行われるで、動的スコプとれます。
772の変数B<そサブルチンからび出さた関数から参照できます>
773これはコンパイル時ではなく、実行時に行われます。
1203774local() は常にグローバル変数に対して作用し、
1204パッケージ変数とか動的変数と呼ばれることもあります。
775パッケージ変数とか動的変数(dynamic variables)と呼ばれることもあります。
1205776
1206777=begin original
1207778
1208779C<my($x)> creates a new variable that is only visible in the current
1209780subroutine. This is done at compile-time, so it is called lexical or
1210781static scoping. my() always affects private variables, also called
1211782lexical variables or (improperly) static(ly scoped) variables.
1212783
1213784=end original
1214785
1215C<my($x)> は、現在のサブルーチンにおいてのみ参照できる変数を新たに
786C<my($x)>は、現在のサブルーチンにおいてのみ参照できる変数を新たに生成します。
1216生成します。
1217787これはコンパイル時に行われるので、レキシカルスコープだとか
1218静的スコープと呼ばれます。
788静的スコープと呼ばれます。my()はプライベート変数に作用し、
1219my() はプライベート変数に作用し、レキシカル変数とか(間違って)静的
789レキシカル変数とか(間違って)静的(スコープを持った)変数と呼ばれることもあります。
1220(スコープを持った)変数と呼ばれることもあります。
1221790
1222=begin original
1223
1224For instance:
1225
1226=end original
1227
1228791例を挙げましょう:
1229792
1230 sub visible {
793 sub visible {
1231 print "var has value $var\n";
794 print "var has value $var\n";
1232 }
795 }
1233796
1234 sub dynamic {
797 sub dynamic {
1235 local $var = 'local'; # new temporary value for the still-global
798 local $var = 'local'; # $var という名前の変数の新たなす
1236 visible(); # variable called $var
799 visible(); # テンポラリ値はまだグローバルです
1237 }
800 }
1238801
1239 sub lexical {
802 sub lexical {
1240 my $var = 'private'; # new private variable, $var
803 my $var = 'private'; # 新しいプライベート変数である $var
1241 visible(); # (invisible outside of sub scope)
804 visible(); # (subスコープの外側では不可視です)
1242 }
805 }
1243806
1244 $var = 'global';
807 $var = 'global';
1245808
1246 visible(); # prints global
809 visible(); # グローバルなものを出力
1247 dynamic(); # prints local
810 dynamic(); # ローカルなものを出力
1248 lexical(); # prints global
811 lexical(); # グローバルなものを出力
1249812
1250=begin original
1251
1252Notice how at no point does the value "private" get printed. That's
1253because $var only has that value within the block of the lexical()
1254function, and it is hidden from the called subroutine.
1255
1256=end original
1257
1258813"private"という値を出力させる方法がないということに注目してください。
1259これは、$var が関数の lexical() なブロックの内側でのみその値を持っていて、
814これは、$varが関数の lexical()なブロックの内側でのみその値を持っていて、
1260815そこから呼び出されたサブルーチンからは隠されてしまうからです。
1261816
1262=begin original
817まとめると、local()はあなたがプライベートと考えるようなことをローカルな
1263
1264In summary, local() doesn't make what you think of as private, local
1265variables. It gives a global variable a temporary value. my() is
1266what you're looking for if you want private variables.
1267
1268=end original
1269
1270まとめると、local() はあなたがプライベートと考えるようなことをローカルな
1271818変数に対して行うようなことはありません。
1272819これはグローバル変数に一時的な値を与えるだけです。
1273あなたがプライベート変数を必要としている場合、my() があなたが
820my()は、あなたがプライベート変数を必要としているときに探し求めているものです。
1274探し求めているものです。
1275821
1276=begin original
822このことをより詳しく説明している
823See L<perlsub/"Private Variables via my()"> と
1278See L<perlsub/"Private Variables via my()"> and
1279L<perlsub/"Temporary Values via local()"> for excruciating details.
1280
1281=end original
1282
1283このことをより詳しく説明している L<perlsub/"Private Variables via my()"> と
1284824L<perlsub/"Temporary Values via local()"> を参照してください。
1285825
1286826=head2 How can I access a dynamic variable while a similarly named lexical is in scope?
1287827
1288(どうやれば同じ名前のレキシカル変数がスコープにあるときに動的変数にアクセスできますか?)
828(どうやれば同じ名前のlexicalがスコープにあるときに動的変数にアクセスできますか?)
1289829
1290=begin original
830これは、C<use strict "refs">とせずにシンボリックリファレンスを使えばできます。
831ですから、$var ではなく C<${'var'}>を使います
1291832
1292If you know your package, you can just mention it explicitly, as in
833 local $var = "global";
1293$Some_Pack::var. Note that the notation $::var is B<not> the dynamic $var
834 my $var = "lexical";
1294in the current package, but rather the one in the "main" package, as
1295though you had written $main::var.
1296835
1297=end original
836 print "lexical is $var\n";
1298837
1299自分のパッケージを知っているのなら、これを $Some_Pack::var と明示的に
838 no strict 'refs';
1300記述できます。
839 print "global is ${'var'}\n";
1301$::var という記法はカレントパッケージにおける動的な $var ではなく、
1302"main" パッケージの中にあるそれなのだということに注意してください。
1303840
1304 use vars '$var';
841自分のパッケージを知っているのなら、これを $Some_Pack::var と陽に記述できます。
1305 local $var = "global";
842$::var という記法はカレントパッケージにおける動的な$varではなく、
1306 my $var = "lexical";
843C<main>パッケージの中にあるそれなのだということに注意してください。
844パッケージを直接指定することによってその名前をハードコードすることになりますが、
845実行速度を速くし、C<use strict "refs">と衝突することを避けます。
1307846
1308 print "lexical is $var\n";
1309 print "global is $main::var\n";
1310
1311=begin original
1312
1313Alternatively you can use the compiler directive our() to bring a
1314dynamic variable into the current lexical scope.
1315
1316=end original
1317
1318あるいは、動的変数を現在のレキシカルスコープにもたらすために、コンパイラ
1319指示子 our() を使えます。
1320
1321 require 5.006; # our() did not exist before 5.6
1322 use vars '$var';
1323
1324 local $var = "global";
1325 my $var = "lexical";
1326
1327 print "lexical is $var\n";
1328
1329 {
1330 our $var;
1331 print "global is $var\n";
1332 }
1333
1334847=head2 What's the difference between deep and shallow binding?
1335848
1336849(深い束縛(deep binding)と浅い束縛(shallow binding)との間の違いとは?)
1337850
1338=begin original
851深い束縛では、無名サブルーチンに置かれているleical変数はそのサブルーチンが
852生成されたときのものと同一のものになります。
1340In deep binding, lexical variables mentioned in anonymous subroutines
853浅い束縛では、これはそのサブルーチンが呼び出されたときのスコープに存在している
1341are the same ones that were in scope when the subroutine was created.
854同じ名前を持った変数のどれか、になります。
1342In shallow binding, they are whichever variables with the same names
855Perl はレキシカル変数(つまり、my()によって作られるもの)に対しては
1343happen to be in scope when the subroutine is called. Perl always uses
1344deep binding of lexical variables (i.e., those created with my()).
1345However, dynamic variables (aka global, local, or package variables)
1346are effectively shallowly bound. Consider this just one more reason
1347not to use them. See the answer to L<"What's a closure?">.
1348
1349=end original
1350
1351深い束縛では、無名サブルーチンに置かれているレキシカル変数は
1352そのサブルーチンが生成されたときのものと同一のものになります。
1353浅い束縛では、これはそのサブルーチンが呼び出されたときのスコープに
1354存在している同じ名前を持った変数のどれか、になります。
1355Perl はレキシカル変数(つまり、my() によって作られるもの)に対しては
1356856常に深い束縛を使います。
1357それに対し動的変数(つまりグローバル変数か、ローカル変数か、
857それに対し動的変数(つまりグローバル変数か、ローカル変数か、パッケージ変数)では、
1358パッケージ変数)では、浅い束縛がなされます。
858浅い束縛がなされます。
1359859こういったものを使わない理由がもう一つあります。
1360その答えは L<"What's a closure?"> を参照してください。
860その答えは L<"What's a closure?">を参照してください。
1361861
1362=head2 Why doesn't "my($foo) = E<lt>FILEE<gt>;" work right?
862=head2 Why doesn't "my($foo) = <FILE>;" work right?
1363863
1364(なぜ "my($foo) = E<lt>FILEE<gt>;" が正しく動作しないのでしょうか?)
864(なぜ "my($foo) = <FILE>;" が正しく動作しないのでしょうか?)
1365865
1366=begin original
866C<my()>とC<local()>はC<=>の右辺に対してリストコンテキストを与えます。
867読み込み操作 <FH>は Perlの関数や演算子の多くと同じくそれが呼び出されたときの
1368C<my()> and C<local()> give list context to the right hand side
1369of C<=>. The <FH> read operation, like so many of Perl's
1370functions and operators, can tell which context it was called in and
1371behaves appropriately. In general, the scalar() function can help.
1372This function does nothing to the data itself (contrary to popular myth)
1373but rather tells its argument to behave in whatever its scalar fashion is.
1374If that function doesn't have a defined scalar behavior, this of course
1375doesn't help you (such as with sort()).
1376
1377=end original
1378
1379C<my()> と C<local()> は C<=> の右辺に対してリストコンテキストを与えます。
1380読み込み操作 <FH> は Perlの関数や演算子の多くと同じくそれが呼び出されたときの
1381868コンテキストを見分けることができて、それに応じて適切に振る舞います。
1382一般的には、scalar() 関数が助けになるでしょう。
869一般的には、scalar()関数が助けになるでしょう。
1383その関数は(一般的な神話とは反して)引数となるデータに対して
870その関数は(一般的な神話(myth)とは反して)引数となるデータに対して
1384何も行いませんが、引数がスカラとして振る舞うように指示します。
871何も行いませんが、引数がスカラとして振る舞うように指示します。
1385関数のスカラ時の振る舞いが定義されていないのであれば、
872関数のスカラ時の振る舞いが定義されていないのであれば、
1386当然ながらこれはあなたの助けにはなりません(sort() がそうです)。
873当然ながらこれはあなたの助けにはなりません(sort()がそうです)。
1387874
1388=begin original
875しかしながら特定のケースにおいては、スカラーコンテキストを強制するために
1389
1390To enforce scalar context in this particular case, however, you need
1391merely omit the parentheses:
1392
1393=end original
1394
1395しかしながら特定のケースにおいては、スカラコンテキストを強制するために
1396876単に括弧を取り除く必要があります:
1397877
1398 local($foo) = <FILE>; # WRONG
878 local($foo) = <FILE>; # 間違い
1399 local($foo) = scalar(<FILE>); # ok
879 local($foo) = scalar(<FILE>); # ok
1400 local $foo = <FILE>; # right
880 local $foo = <FILE>; # 正しい
1401881
1402=begin original
1403
1404You should probably be using lexical variables anyway, although the
1405issue is the same here:
1406
1407=end original
1408
1409882これと同じ問題があるものの、なんにしろレキシカル変数を使うべきでしょう。
1410883
1411 my($foo) = <FILE>; # WRONG
884 my($foo) = <FILE>; # 間違い
1412 my $foo = <FILE>; # right
885 my $foo = <FILE>; # 正しい
1413886
1414887=head2 How do I redefine a builtin function, operator, or method?
1415888
1416889(組み込みの関数や演算子、メソッドを再定義するには?)
1417890
1418=begin original
1419
1420Why do you want to do that? :-)
1421
1422=end original
1423
1424891なんだってそんなことをしたがるのですか? :-)
1425892
1426=begin original
893open()のようなあらかじめ定義されている関数をオーバーライドしたいのであれば、
894異なるモジュールから新しい定義をimportする必要があるでしょう。
895L<perlsub/"Overriding Built-in Functions">を参照してください。
896L<perltoot/"Class::Template">にも例があります。
1427897
1428If you want to override a predefined function, such as open(),
898C<+> C<**>のようなPerlの演算子をオーバーロードしたいのであれば
1429then you'll have to import the new definition from a different
899L<overload>で説明されているような C<use overload>プラグマを使いたくなるでしょう。
1430module. See L<perlsub/"Overriding Built-in Functions">.
1431900
1432=end original
901親クラス郡における不明瞭なメソッド呼び出しについて考えているのなら、
902L<perltoot/"Overridden Methods">を参照してください。
1433903
1434open() のようなあらかじめ定義されている関数をオーバーライドしたいのであれば、
1435異なるモジュールから新しい定義をインポートする必要があります。
1436L<perlsub/"Overriding Built-in Functions"> を参照してください。
1437
1438=begin original
1439
1440If you want to overload a Perl operator, such as C<+> or C<**>,
1441then you'll want to use the C<use overload> pragma, documented
1442in L<overload>.
1443
1444=end original
1445
1446C<+> や C<**> のような Perl の演算子をオーバーロードしたいのであれば
1447L<overload> で説明されているような C<use overload> プラグマを
1448使いたくなるでしょう。
1449
1450=begin original
1451
1452If you're talking about obscuring method calls in parent classes,
1453see L<perltoot/"Overridden Methods">.
1454
1455=end original
1456
1457親クラスにおける不明瞭なメソッド呼び出しについて考えているのなら、
1458L<perltoot/"Overridden Methods"> を参照してください。
1459
1460904=head2 What's the difference between calling a function as &foo and foo()?
1461905
1462(関数呼び出しを &foo で行ったときと foo() で行ったときとの違いはなんですか?)
906(関数呼び出しを &fooで行ったときとfoo()で行ったときとの違いはなんですか?)
1463907
1464=begin original
908関数を C<&foo>として呼び出したとき、その関数はプロトタイプを無視して
909カレントの@_の値全てにアクセスすることができます。
910これはつまり、空の@_を受け取るのではなくてあなたが使っていた
911それを受け取るということなのです!
912これは厳密にバグとは考えられていませんが(L<perlsub>に説明があります)、
913ほとんどの場合はこの機能が使われるとは考えられないでしょう。
1465914
1466(contributed by brian d foy)
915C<&foo()>のように関数を呼び出した場合には新たな @_を受け取りますが、
916この場合もプロトタイプは無視されます。
1467917
1468=end original
918通常は、関数を C<foo()>のように呼び出したいでしょう。
919既に定義がされていたり(C<require> ではなくC<use>)、先行宣言を使っていたり、
920C<use subs> 宣言などがあってコンパイラーが既にその関数を知っているときにのみ
921括弧を省略することができます。
922この場合でさえ、そこにあるべきでない古い値が漏れだしていることのない
923クリーンな @_ を得られます。
1469924
1470(brian d foy によって寄贈されました)
1471
1472=begin original
1473
1474Calling a subroutine as C<&foo> with no trailing parentheses ignores
1475the prototype of C<foo> and passes it the current value of the argument
1476list, C<@_>. Here's an example; the C<bar> subroutine calls C<&foo>,
1477which prints its arguments list:
1478
1479=end original
1480
1481C<&foo> の形で、引き続くかっこなしでサブルーチンを呼び出すと、
1482C<foo> のプロトタイプを無視して、引数リスト C<@_> の現在の値を渡します。
1483以下は例です: C<bar> サブルーチンは、引数リストを表示する C<&foo> を
1484呼び出します:
1485
1486 sub bar { &foo }
1487
1488 sub foo { print "Args in foo are: @_\n" }
1489
1490 bar( qw( a b c ) );
1491
1492=begin original
1493
1494When you call C<bar> with arguments, you see that C<foo> got the same C<@_>:
1495
1496=end original
1497
1498C<bar> を引数付きで呼び出した場合、C<foo> も同じ C<@_> を得ます:
1499
1500 Args in foo are: a b c
1501
1502=begin original
1503
1504Calling the subroutine with trailing parentheses, with or without arguments,
1505does not use the current C<@_> and respects the subroutine prototype. Changing
1506the example to put parentheses after the call to C<foo> changes the program:
1507
1508=end original
1509
1510サブルーチンをかっこ付きで呼び出した場合、引数のありなしに関わらず、
1511現在の C<@_> は使わずに、サブルーチンのプロトタイプに従います。
1512C<foo> を呼び出すときにかっこをつけるように例を変更します:
1513
1514 sub bar { &foo() }
1515
1516 sub foo { print "Args in foo are: @_\n" }
1517
1518 bar( qw( a b c ) );
1519
1520=begin original
1521
1522Now the output shows that C<foo> doesn't get the C<@_> from its caller.
1523
1524=end original
1525
1526今度は、C<foo> が呼び出し元から C<@_> を得ていないことが分かります:
1527
1528 Args in foo are:
1529
1530=begin original
1531
1532The main use of the C<@_> pass-through feature is to write subroutines
1533whose main job it is to call other subroutines for you. For further
1534details, see L<perlsub>.
1535
1536=end original
1537
1538C<@_> パススルー機能の主な利用法は、他のサブルーチンを呼び出すのが
1539主な仕事であるサブルーチンを書くためです。
1540更なる詳細については、L<perlsub> を参照してください。
1541
1542925=head2 How do I create a switch or case statement?
1543926
1544(switch 文や case 文を作るには?)
927(switch文やcase文を作るには?)
1545928
1546=begin original
929これは L<perlsyn>でより詳細に説明されています。
930簡単にいうと、Perl では様々なやり方(数値比較、文字列比較、グロブ比較、
931正規表現マッチング、オーバーロードされた比較…)で検査が行えるので、
932正式な case 文はありません。
933Larry はこのどれが最善であるかを決めることができないので、
934perl1 の時代から wish リストに置かれているにも関らずこの問題は
935そのままにしておかれているのです。
1547936
1548In Perl 5.10, use the C<given-when> construct described in L<perlsyn>:
937構造文を書くための一般的な答えは以下のようなものです:
1549938
1550=end original
939 for ($variable_to_test) {
940 if (/pat1/) { } # 何かを行う
941 elsif (/pat2/) { } # 別の何かを行う
942 elsif (/pat3/) { } # 別の何かを行う
943 else { } # デフォルト
944 }
1551945
1552Perl 5.10 では、L<perlsyn> 記述されてる C<given-when> 構造を
946以下の例は、パターンマッチング基づた単純なswitchの例です。
1553使ってください:
947$whatchamacallitに格納れたリファレンスの型に基づて多様なやり方の
1554
1555 use 5.010;
1556
1557 given ( $string ) {
1558 when( 'Fred' ) { say "I found Fred!" }
1559 when( 'Barney' ) { say "I found Barney!" }
1560 when( /Bamm-?Bamm/ ) { say "I found Bamm-Bamm!" }
1561 default { say "I don't recognize the name!" }
1562 };
1563
1564=begin original
1565
1566If one wants to use pure Perl and to be compatible with Perl versions
1567prior to 5.10, the general answer is to use C<if-elsif-else>:
1568
1569=end original
1570
1571もしピュア Perl を使って、バージョン 5.10 より前と互換性を持たせたいなら、
1572構造文を書くための一般的な答えは C<if-elsif-else> を使うことです:
1573
1574 for ($variable_to_test) {
1575 if (/pat1/) { } # do something
1576 elsif (/pat2/) { } # do something else
1577 elsif (/pat3/) { } # do something else
1578 else { } # default
1579 }
1580
1581=begin original
1582
1583Here's a simple example of a switch based on pattern matching,
1584lined up in a way to make it look more like a switch statement.
1585We'll do a multiway conditional based on the type of reference stored
1586in $whatchamacallit:
1587
1588=end original
1589
1590以下の例は、パターンマッチングに基づいた単純な switch の例です。
1591$whatchamacallit に格納されたリファレンスの型に基づいて多様なやり方の
1592948条件判断を行っています:
1593949
1594950 SWITCH: for (ref $whatchamacallit) {
1595951
1596952 /^$/ && die "not a reference";
1597953
1598954 /SCALAR/ && do {
1599955 print_scalar($$ref);
1600956 last SWITCH;
1601957 };
1602958
1603959 /ARRAY/ && do {
1604960 print_array(@$ref);
1605961 last SWITCH;
1606962 };
1607963
1608964 /HASH/ && do {
1609965 print_hash(%$ref);
1610966 last SWITCH;
1611967 };
1612968
1613969 /CODE/ && do {
1614970 warn "can't print function ref";
1615971 last SWITCH;
1616972 };
1617973
1618974 # DEFAULT
1619975
1620976 warn "User defined type skipped";
1621977
1622978 }
1623979
1624=begin original
980この形式の他の例についてはC<perlsyn/"Basic BLOCKs and Switch Statements">を
981参照してください。
1625982
1626See L<perlsyn> for other examples in this style.
1627
1628=end original
1629
1630このスタイルに関するその他の例については L<perlsyn> を参照してください。
1631
1632983=begin original
1633984
1634985Sometimes you should change the positions of the constant and the variable.
1635986For example, let's say you wanted to test which of many answers you were
1636987given, but in a case-insensitive way that also allows abbreviations.
1637988You can use the following technique if the strings all start with
1638989different characters or if you want to arrange the matches so that
1639990one takes precedence over another, as C<"SEND"> has precedence over
1640991C<"STOP"> here:
1641992
1642993=end original
1643994
1644995定数や変数の位置を変えた方が良いことがあるかもしれません。
1645996たとえば、与えられたたくさんの答についてテストを行いたいとしましょう。
1646997この場合大小文字を無視することもできますし、
1647998略記することもあります。もし全て文字列が異なるキャラクターで始まっていたり、
1648C<"SEND"> C<"STOP"> より高い優先順位を持つように調整したくいのなら
999C<"SEND">がC<"STOP">
1649マッチのアレンジしたいのであれば以下に示すようテクニ
1000より高い優先持つように調整したいのならマチの順序
1650使うことができます。
1001アレンジしたいのであれば以下に示すようなテクニックを使うことができます。
16511002
1652 chomp($answer = <>);
1003 chomp($answer = <>);
1653 if ("SEND" =~ /^\Q$answer/i) { print "Action is send\n" }
1004 if ("SEND" =~ /^\Q$answer/i) { print "Action is send\n" }
1654 elsif ("STOP" =~ /^\Q$answer/i) { print "Action is stop\n" }
1005 elsif ("STOP" =~ /^\Q$answer/i) { print "Action is stop\n" }
1655 elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" }
1006 elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" }
1656 elsif ("LIST" =~ /^\Q$answer/i) { print "Action is list\n" }
1007 elsif ("LIST" =~ /^\Q$answer/i) { print "Action is list\n" }
1657 elsif ("EDIT" =~ /^\Q$answer/i) { print "Action is edit\n" }
1008 elsif ("EDIT" =~ /^\Q$answer/i) { print "Action is edit\n" }
16581009
1659=begin original
1660
1661A totally different approach is to create a hash of function references.
1662
1663=end original
1664
16651010まったく異なるアプローチに、関数のリファレンスのハッシュを作成するという
16661011やり方があります。
16671012
1668 my %commands = (
1013 my %commands = (
1669 "happy" => \&joy,
1014 "happy" => \&joy,
1670 "sad", => \&sullen,
1015 "sad", => \&sullen,
1671 "done" => sub { die "See ya!" },
1016 "done" => sub { die "See ya!" },
1672 "mad" => \&angry,
1017 "mad" => \&angry,
1673 );
1018 );
16741019
1675 print "How are you? ";
1020 print "How are you? ";
1676 chomp($string = <STDIN>);
1021 chomp($string = <STDIN>);
1677 if ($commands{$string}) {
1022 if ($commands{$string}) {
1678 $commands{$string}->();
1023 $commands{$string}->();
1679 } else {
1024 } else {
1680 print "No such command: $string\n";
1025 print "No such command: $string\n";
1681 }
1026 }
16821027
1683=begin original
1028=head2 How can I catch accesses to undefined variables/functions/methods?
16841029
1685Starting from Perl 5.8, a source filter module, C<Switch>, can also be
1030(どうすれば undefinedな変数/関数/メソッドに対するアクセスを捕捉できますか?)
1686used to get switch and case. Its use is now discouraged, because it's
1687not fully compatible with the native switch of Perl 5.10, and because,
1688as it's implemented as a source filter, it doesn't always work as intended
1689when complex syntax is involved.
16901031
1691=end original
1032L<perlsub/"Autoloading"> と L<perltoot/"AUTOLOAD: Proxy Methods">で
1033言及されている AUTOLOADメソッドは、undefine な関数やメソッドに対する
1034呼び出しを捕捉させてくれます。
16921035
1693Perl 5.8 から、ソースフィルタモジュール C<Switch> も switch case を
1036C<-w>が有効なきに警告の引き金になるような未定義変数へのアクセスがあったとき、
1694使うため使えま
1037以下の例あるような擬似シグナルC<__WARN__>をトラップるハンドラーを
1695Perl 5.10 には完全互換のネイティブな switch あり、た、これはソース
1038使うことできす:
1696フィルタとして実装されているので、複雑な文法の場合はいつも想定通りに
1697動くとは限らないからです。
16981039
1699=head2 How can I catch accesses to undefined variables, functions, or methods?
1040 $SIG{__WARN__} = sub {
17001041
1701(どうすれば未定義な変数, 関数, メソッドに対するアクセスを捕捉できますか?)
1042 for ( $_[0] ) { # voici un switch statement
17021043
1703=begin original
1044 /Use of uninitialized value/ && do {
1045 # 警告をエラーにします
1046 die $_;
1047 };
17041048
1705The AUTOLOAD method, discussed in L<perlsub/"Autoloading"> and
1049 # その他の警告はここで捕捉できます
1706L<perltoot/"AUTOLOAD: Proxy Methods">, lets you capture calls to
1707undefined functions and methods.
17081050
1709=end original
1051 warn $_;
1052 }
17101053
1711L<perlsub/"Autoloading"> L<perltoot/"AUTOLOAD: Proxy Methods"> で
1054 };
1712言及されている AUTOLOAD メソッドは、未定義な関数やメソッドに対する
1713呼び出しを捕捉させてくれます。
17141055
1715=begin original
1716
1717When it comes to undefined variables that would trigger a warning
1718under C<use warnings>, you can promote the warning to an error.
1719
1720=end original
1721
1722C<use warnings> が有効なときに警告の引き金になるような未定義変数への
1723アクセスがあったとき、警告をエラーに昇格させることができます。
1724
1725 use warnings FATAL => qw(uninitialized);
1726
17271056=head2 Why can't a method included in this same file be found?
17281057
17291058(なぜ同じファイルにあるメソッドが見つけられないのでしょうか?)
17301059
1731=begin original
1732
1733Some possible reasons: your inheritance is getting confused, you've
1734misspelled the method name, or the object is of the wrong type. Check
1735out L<perltoot> for details about any of the above cases. You may
1736also use C<print ref($object)> to find out the class C<$object> was
1737blessed into.
1738
1739=end original
1740
17411060幾つかの理由が考えられます: あなたが継承したものが混乱していているか、
17421061メソッド名を間違えたか、あるいはオブジェクトの型が間違っていたか。
17431062上記の場合に関する詳細は L<perltoot> をチェックしてみてください。
1744C<$object> が bless されているクラスは C<print ref($object)> として
1063C<$object> がblessされているクラスは C<print ref($object)>として
17451064見分けることができます。
17461065
1747=begin original
1066もう一つありうる理由は、Perlがパッケージを見いだす前にクラス名を使った
1067間接オブジェクト構文(C<find Guru "Samy">のようなもの)を使ったためでしょう。
1749Another possible reason for problems is that you've used the
1750indirect object syntax (eg, C<find Guru "Samy">) on a class name
1751before Perl has seen that such a package exists. It's wisest to make
1752sure your packages are all defined before you start using them, which
1753will be taken care of if you use the C<use> statement instead of
1754C<require>. If not, make sure to use arrow notation (eg.,
1755C<< Guru->find("Samy") >>) instead. Object notation is explained in
1756L<perlobj>.
1757
1758=end original
1759
1760もう一つありうる理由は、Perl がパッケージを見いだす前にクラス名を使った
1761間接オブジェクト構文(C<find Guru "Samy"> のようなもの)を使ったためでしょう。
17621068パッケージは、それを使うよりも前に全てが定義されているようにします。
1763これは C<require> 文ではなく C<use> 文を使えば考慮されます。
1069これはC<require>文ではなくC<use>文を使えば考慮されます。
17641070あるいは、代わりに矢印記法(arrow notation、
17651071C<< Guru->find("Samy") >> のようなもの)を使うようにしてください。
1766オブジェクトの記法は L<perlobj> で説明されています。
1072オブジェクトの記法はL<perlobj>で説明されています。
17671073
17681074=begin original
17691075
17701076Make sure to read about creating modules in L<perlmod> and
1771the perils of indirect objects in L<perlobj/"Method Invocation">.
1077the perils of indirect objects in L<perlobj/"WARNING">.
17721078
17731079=end original
17741080
1775モジュールの作り方については L<perlmod> を、間接オブジェクトの問題点に
1081モジュールの作り方については L<perlmod> を、
1776ついては L<perlobj/"WARNING"> を確認してください。
1082間接オブジェクトの問題点については L<perlobj/"WARNING"> を
1083確認してください。
17771084
1778=head2 How can I find out my current or calling package?
1085=head2 How can I find out my current package?
17791086
1780(カレントのパッケージや呼び出しパッケージはどうすればわかりますか?)
1087(カレントのパッケージはどうすればわかりますか?)
17811088
1782=begin original
1089ランダムなプログラムであるなら、以下のようにすれば現在コンパイルされている
1090パッケージを知ることができます:
17831091
1784(contributed by brian d foy)
1092 my $packname = __PACKAGE__;
17851093
1786=end original
1787
1788(brian d foy によって寄贈されました)
1789
17901094=begin original
17911095
1792To find the package you are currently in, use the special literal
1096But, if you're a method and you want to print an error message
1793C<__PACKAGE__>, as documented in L<perldata>. You can only use the
1097that includes the kind of object you were called on (which is
1794special literals as separate tokens, so you can't interpolate them
1098not necessarily the same as the one in which you were compiled):
1795into strings like you can with variables:
17961099
17971100=end original
17981101
1799今いるパケージを知るにはL<perldata> に記述されてい特殊リテラル
1102しかし、対象がメソドで呼び出されたオブジェクトの種類がなんであかを
1800C<__PACKAGE__> を使ってく
1103含んエラーメッセージを出力したのなら(これはそれが
1801特殊リテラは独立しトークンとしてみ使えるの、変数のように
1104コンパイされと同一ある必要はありません):
1802文字列に展開できません:
18031105
1804 my $current_package = __PACKAGE__;
1805 print "I am in package $current_package\n";
18061106
1807=begin original
1107 sub amethod {
1108 my $self = shift;
1109 my $class = ref($self) || $self;
1110 warn "called me from a $class object";
1111 }
18081112
1809If you want to find the package calling your code, perhaps to give better
1113=head2 How can I comment out a large block of perl code?
1810diagnostics as C<Carp> does, use the C<caller> built-in:
18111114
1812=end original
1115(perlプログラムの大きなブロックをコメントアウトするのは
1116どうすればできますか?)
18131117
1814あるコード呼び出したパッケージを知りたい場合 (おそらく C<Carp> よう
1118埋め込みのPOD説明ため使います:
1815よりよい診断メッセージのためでしょう) C<caller> 組み込み関数を
1816使ってください:
18171119
1818 sub foo {
1120 # プログラムはここに
1819 my @args = ...;
1820 my( $package, $filename, $line ) = caller;
18211121
1822 print "I was called from package $package\n";
1122 =for nobody
1823 );
1123 このパラグラフはコメントアウトされます
18241124
1825=begin original
1125 # プログラムの続き
18261126
1827By default, your program starts in package C<main>, so you will
1127 =begin comment text
1828always be in some package.
18291128
1830=end original
1129 ここにあるものすべては
18311130
1832デフォルトでは、プログラムはパッケージ C<main> で開始されるので、
1131 なにからも無視されます
1833いつもなんらかのパッケージ内にいるはずです。
18341132
1835=begin original
1133 =end comment text
18361134
1837This is different from finding out the package an object is blessed
1135 =cut
1838into, which might not be the current package. For that, use C<blessed>
1839from C<Scalar::Util>, part of the Standard Library since Perl 5.8:
18401136
1841=end original
1842
1843これはオブジェクトが bless されているパッケージを知ることとは違います;
1844これは現在のパッケージではないかもしれません。
1845この目的のためには、Perl 5.8 から標準ライブラリの一部となっている
1846C<Scalar::Util> の C<blessed> を使ってください:
1847
1848 use Scalar::Util qw(blessed);
1849 my $object_package = blessed( $object );
1850
18511137=begin original
18521138
1853Most of the time, you shouldn't care what package an object is blessed
1139This can't go just anywhere. You have to put a pod directive where
1854into, however, as long as it claims to inherit from that class:
1140the parser is expecting a new statement, not just in the middle
1141of an expression or some other arbitrary yacc grammar production.
18551142
18561143=end original
18571144
1858しかし、ほとんの場合では、オブジェクトそのクラスから継承していると
1145これはこにも置けるわけでありません。パーザー
1859主張る限りは、どのパッケジが bless たか
1146しいステトメントを期待ている場所にpod指令置く必要があって、
1860気にするべきません:
1147式の途中であるとかその他任意の yacc 文法生成規則には置けません
18611148
1862 my $is_right_class = eval { $object->isa( $package ) }; # true or false
1863
1864=begin original
1865
1866And, with Perl 5.10 and later, you don't have to check for an
1867inheritance to see if the object can handle a role. For that, you can
1868use C<DOES>, which comes from C<UNIVERSAL>:
1869
1870=end original
1871
1872また、Perl 5.10 以降では、オブジェクトがロールを扱うかどうかを見るために
1873継承をチェックする必要はありません。
1874このために、C<UNIVERSAL> にある C<DOES> を使えます:
1875
1876 my $class_does_it = eval { $object->DOES( $role ) }; # true or false
1877
1878=begin original
1879
1880You can safely replace C<isa> with C<DOES> (although the converse is not true).
1881
1882=end original
1883
1884安全に C<isa> を C<DOES> に置き換えられます (しかし逆は真ではありません)。
1885
1886=head2 How can I comment out a large block of Perl code?
1887
1888(Perl プログラムの大きなブロックをコメントアウトするには?)
1889
1890=begin original
1891
1892(contributed by brian d foy)
1893
1894=end original
1895
1896(brian d foy によって寄贈されました)
1897
1898=begin original
1899
1900The quick-and-dirty way to comment out more than one line of Perl is
1901to surround those lines with Pod directives. You have to put these
1902directives at the beginning of the line and somewhere where Perl
1903expects a new statement (so not in the middle of statements like the #
1904comments). You end the comment with C<=cut>, ending the Pod section:
1905
1906=end original
1907
1908Perl の複数行をコメントアウトするための、汚いけれども簡単な方法は、
1909コメントアウトしたい部分を Pod 指示子で囲むことです。
1910これらの指示子は、行の先頭、かつ、Perl が新しい文が始まると
1911想定する場所に置く必要があります(従って、# コメントのように文の途中には
1912置けません)。
1913Pod セクションの終了を示す C<=cut> でコメントを終了します:
1914
1915 =pod
1916
1917 my $object = NotGonnaHappen->new();
1918
1919 ignored_sub();
1920
1921 $wont_be_assigned = 37;
1922
1923 =cut
1924
1925=begin original
1926
1927The quick-and-dirty method only works well when you don't plan to
1928leave the commented code in the source. If a Pod parser comes along,
1929you're multiline comment is going to show up in the Pod translation.
1930A better way hides it from Pod parsers as well.
1931
1932=end original
1933
1934汚いけれども簡単な方法は、ソースにコメントされたコードを残す予定が
1935ない(つまりいずれ消す)場合にのみうまく働きます。
1936もし Pod パーサを使うと、複数行コメントは Pod によって表示されます。
1937よりよい方法は、Pod パーサからも隠すことです。
1938
1939=begin original
1940
1941The C<=begin> directive can mark a section for a particular purpose.
1942If the Pod parser doesn't want to handle it, it just ignores it. Label
1943the comments with C<comment>. End the comment using C<=end> with the
1944same label. You still need the C<=cut> to go back to Perl code from
1945the Pod comment:
1946
1947=end original
1948
1949C<=begin> 指示子で、段落を特定の目的のためにマークできます。
1950Pod パーサがこれを扱えない場合、単に無視されます。
1951コメントは C<comment> でラベル付けします。
1952コメントの終了は同じラベルで C<=end> を使います。
1953Pod コメントから Perl コードに戻るにはやはり C<=cut> が必要です:
1954
1955 =begin comment
1956
1957 my $object = NotGonnaHappen->new();
1958
1959 ignored_sub();
1960
1961 $wont_be_assigned = 37;
1962
1963 =end comment
1964
1965 =cut
1966
1967=begin original
1968
1969For more information on Pod, check out L<perlpod> and L<perlpodspec>.
1970
1971=end original
1972
1973Pod に関するさらなる情報については、L<perlpod> と L<perlpodspec> を
1974調べてください。
1975
19761149=head2 How do I clear a package?
19771150
19781151(パッケージをクリアするには?)
19791152
1980=begin original
1153Mark-Jason Dominusによる以下のコードを使います:
19811154
1982Use this code, provided by Mark-Jason Dominus:
19831155
1984=end original
1156 sub scrub_package {
1157 no strict 'refs';
1986Mark-Jason Dominus による以下のコードを使います:
1158 my $pack = shift;
1159 die "Shouldn't delete main package"
1988 sub scrub_package {
1160 if $pack eq "" || $pack eq "main";
1989 no strict 'refs';
1161 my $stash = *{$pack . '::'}{HASH};
1990 my $pack = shift;
1162 my $name;
1991 die "Shouldn't delete main package"
1163 foreach $name (keys %$stash) {
1992 if $pack eq "" || $pack eq "main";
1164 my $fullname = $pack . '::' . $name;
1993 my $stash = *{$pack . '::'}{HASH};
1165 # 名前に関する全てのものを取り去る
1994 my $name;
1166 undef $$fullname;
1995 foreach $name (keys %$stash) {
1167 undef @$fullname;
1996 my $fullname = $pack . '::' . $name;
1168 undef %$fullname;
1997 # Get rid of everything with that name.
1169 undef &$fullname;
1998 undef $$fullname;
1170 undef *$fullname;
1999 undef @$fullname;
2000 undef %$fullname;
2001 undef &$fullname;
2002 undef *$fullname;
20031171 }
2004 }
1172 }
20051173
2006=begin original
2007
2008Or, if you're using a recent release of Perl, you can
2009just use the Symbol::delete_package() function instead.
2010
2011=end original
2012
20131174あるいは、あなたが使っている Perl が最近のリリースのものであれば、
20141175単に Symbol::delete_package() という関数を代わりに使うことができます。
20151176
20161177=head2 How can I use a variable as a variable name?
20171178
2018(変数を変数名として使うには?)
1179(変数を変数名として使うにはどうすればいいですか?)
20191180
20201181=begin original
20211182
20221183Beginners often think they want to have a variable contain the name
20231184of a variable.
20241185
20251186=end original
20261187
20271188初心者はしばしば変数名が入った変数を使いたいと考えます。
20281189
2029 $fred = 23;
1190 $fred = 23;
2030 $varname = "fred";
1191 $varname = "fred";
2031 ++$$varname; # $fred now 24
1192 ++$$varname; # $fred now 24
20321193
20331194=begin original
20341195
20351196This works I<sometimes>, but it is a very bad idea for two reasons.
20361197
20371198=end original
20381199
2039これは I<時には> 動作します。
1200これはI<時には>動作します。しかしこれは二つの理由により悪いアイデアです。
2040しかしこれは二つの理由により悪いアイデアです。
20411201
20421202=begin original
20431203
20441204The first reason is that this technique I<only works on global
20451205variables>. That means that if $fred is a lexical variable created
20461206with my() in the above example, the code wouldn't work at all: you'd
20471207accidentally access the global and skip right over the private lexical
20481208altogether. Global variables are bad because they can easily collide
20491209accidentally and in general make for non-scalable and confusing code.
20501210
20511211=end original
20521212
2053一つ目の理由は、このテクニックは I<グローバル変数でのみ動作する> からです。
1213一つ目の理由は、このテクニックはI<グローバル変数でのみ動作する>からです。
20541214つまり、もし上記の例において $fred が my() で作成されたレキシカル変数の場合、
2055このコードは全く動作しません。
1215このコードは全く動作しません。プライベートなレキシカル変数を飛ばして、
2056プライベートなレキシカル変数を飛ばして、思いがけずグローバル変数に
1216思いがけずグローバル変数にアクセスすることになります。
2057アクセスすることになります。
20581217グローバル変数は、簡単に衝突し、一般に拡張性がなく、混乱するコードを
20591218作ることになるので、よくないものです。
20601219
20611220=begin original
20621221
20631222Symbolic references are forbidden under the C<use strict> pragma.
2064They are not true references and consequently are not reference-counted
1223They are not true references and consequently are not reference counted
2065or garbage-collected.
1224or garbage collected.
20661225
20671226=end original
20681227
20691228シンボリックリファレンスは C<use strict> プラグマの元では禁止されます。
20701229これは真のリファレンスではないので、リファレンスカウントに含まれず、
20711230ガベージゴレクションもされません。
20721231
20731232=begin original
20741233
20751234The other reason why using a variable to hold the name of another
20761235variable is a bad idea is that the question often stems from a lack of
20771236understanding of Perl data structures, particularly hashes. By using
20781237symbolic references, you are just using the package's symbol-table hash
20791238(like C<%main::>) instead of a user-defined hash. The solution is to
20801239use your own hash or a real reference instead.
20811240
20821241=end original
20831242
20841243変数に他の変数の名前を記録するというのがよくない考えであるという
20851244別の理由としては、このような疑問はしばしば Perl のデータ構造、
20861245特にハッシュに関する理解の不足から発生するからです。
2087シンボリックリファレンスを使うことによって、ユーザー定義のハッシュの代わりに
1246シンボリックリファレンスを使うことによって、
2088パッケージのシンボルテーブルハッシュ(C<%main::> など)を使うことができます。
1247ユーザー定義のハッシュの代わりにパッケージのシンボルテーブルハッシュ
1248(C<%main::> など)を使うことができます。
20891249解決法は、代わりに自分自身のハッシュや真のリファレンスを使うことです。
20901250
2091 $USER_VARS{"fred"} = 23;
1251 $fred = 23;
2092 $varname = "fred";
1252 $varname = "fred";
2093 $USER_VARS{$varname}++; # not $$varname++
1253 $USER_VARS{$varname}++; # not $$varname++
20941254
20951255=begin original
20961256
20971257There we're using the %USER_VARS hash instead of symbolic references.
20981258Sometimes this comes up in reading strings from the user with variable
20991259references and wanting to expand them to the values of your perl
21001260program's variables. This is also a bad idea because it conflates the
21011261program-addressable namespace and the user-addressable one. Instead of
21021262reading a string and expanding it to the actual contents of your program's
21031263own variables:
21041264
21051265=end original
21061266
2107ここではシンボリックリファレンスの代わりに %USER_VARS ハッシュを
1267ここではシンボリックリファレンスの代わりに %USER_VARS ハッシュを使っています。
2108使っています。
21091268時々これはユーザーから文字列を変数へのリファレンスとして読み込んで、
21101269それを perl プログラムの変数の値として拡張することがあります。
2111これもよくない考えです。
1270これもよくない考えです。なぜなら、プログラムが指定する名前空間と
2112なぜなら、プログラムが指定する名前空間とユーザーが指定する名前空間を
1271ユーザーが指定する名前空間を融合させることになるからです。
2113融合させることになるからです。
21141272以下のように文字列を読み込んであなたのプログラムの変数の実際の内容の
21151273ために拡張するのではなく:
21161274
2117 $str = 'this has a $fred and $barney in it';
2118 $str =~ s/(\$\w+)/$1/eeg; # need double eval
21191275
1276 $str = 'this has a $fred and $barney in it';
1277 $str =~ s/(\$\w+)/$1/eeg; # need double eval
1278
21201279=begin original
21211280
21221281it would be better to keep a hash around like %USER_VARS and have
21231282variable references actually refer to entries in that hash:
21241283
21251284=end original
21261285
2127%USER_VARS のようなハッシュを保存し、このハッシュのエントリを参照する
1286%USER_VARS のようなハッシュを保存し、このハッシュの
2128変数リファレンスを持つよりよい方法です:
1287エントリを参照する変数リファレンスを持つよりよい方法です:
21291288
2130 $str =~ s/\$(\w+)/$USER_VARS{$1}/g; # no /e here at all
1289 $str =~ s/\$(\w+)/$USER_VARS{$1}/g; # no /e here at all
21311290
21321291=begin original
21331292
21341293That's faster, cleaner, and safer than the previous approach. Of course,
21351294you don't need to use a dollar sign. You could use your own scheme to
21361295make it less confusing, like bracketed percent symbols, etc.
21371296
21381297=end original
21391298
21401299これは前述の手法よりも、より高速で、より明快で、より安全です。
21411300もちろん、ドル記号を使う必要はありません。
21421301パーセント記号で囲むなどのより混乱しにくい独自のスキームを使えます。
21431302
2144 $str = 'this has a %fred% and %barney% in it';
1303 $str = 'this has a %fred% and %barney% in it';
2145 $str =~ s/%(\w+)%/$USER_VARS{$1}/g; # no /e here at all
1304 $str =~ s/%(\w+)%/$USER_VARS{$1}/g; # no /e here at all
21461305
21471306=begin original
21481307
21491308Another reason that folks sometimes think they want a variable to
2150contain the name of a variable is that they don't know how to build
1309contain the name of a variable is because they don't know how to build
21511310proper data structures using hashes. For example, let's say they
21521311wanted two hashes in their program: %fred and %barney, and that they
21531312wanted to use another scalar variable to refer to those by name.
21541313
21551314=end original
21561315
21571316人々が時々変数名が入った変数を欲しがるもう一つの理由は、
21581317ハッシュを使った適切なデータ構造を構築する方法を知らないからです。
2159例えば、プログラムで %fred %barney が必要で、
1318例えば、プログラムで%fredと%barneyが必要で、
21601319さらにこれらを名前で参照するスカラへ変数が必要だとします。
21611320
2162 $name = "fred";
1321 $name = "fred";
2163 $$name{WIFE} = "wilma"; # set %fred
1322 $$name{WIFE} = "wilma"; # set %fred
21641323
2165 $name = "barney";
1324 $name = "barney";
2166 $$name{WIFE} = "betty"; # set %barney
1325 $$name{WIFE} = "betty"; # set %barney
21671326
21681327=begin original
21691328
21701329This is still a symbolic reference, and is still saddled with the
21711330problems enumerated above. It would be far better to write:
21721331
21731332=end original
21741333
21751334これはやはりシンボリックリファレンスで、やはり上記の問題を抱えたままです。
21761335以下のように書けば遥かに改善します:
21771336
2178 $folks{"fred"}{WIFE} = "wilma";
1337 $folks{"fred"}{WIFE} = "wilma";
2179 $folks{"barney"}{WIFE} = "betty";
1338 $folks{"barney"}{WIFE} = "betty";
21801339
21811340=begin original
21821341
21831342And just use a multilevel hash to start with.
21841343
21851344=end original
21861345
21871346そして始めるのに単に多段ハッシュを使います。
21881347
21891348=begin original
21901349
21911350The only times that you absolutely I<must> use symbolic references are
21921351when you really must refer to the symbol table. This may be because it's
2193something that one can't take a real reference to, such as a format name.
1352something that can't take a real reference to, such as a format name.
21941353Doing so may also be important for method calls, since these always go
21951354through the symbol table for resolution.
21961355
21971356=end original
21981357
21991358唯一あなたが完全にシンボリックリファレンスを I<使わなければならない> 場合は、
22001359シンボルテーブルに対するリファレンスが必要なときだけです。
22011360これは、フォーマット名といったものに対する真のリファレンスを得ることが
22021361できないからです。
22031362そうすることはメソッド呼び出しのためにも重要です。
22041363なぜなら名前解決のためにシンボルテーブルを使うからです。
22051364
22061365=begin original
22071366
22081367In those cases, you would turn off C<strict 'refs'> temporarily so you
22091368can play around with the symbol table. For example:
22101369
22111370=end original
22121371
22131372これらの場合、一時的に C<strict 'refs'> にして
2214シンボルテーブルを使うようにできます。
1373シンボルテーブルを使うようにできます。例えば:
2215例えば:
22161374
2217 @colors = qw(red blue green yellow orange purple violet);
1375 @colors = qw(red blue green yellow orange purple violet);
2218 for my $name (@colors) {
1376 for my $name (@colors) {
2219 no strict 'refs'; # renege for the block
1377 no strict 'refs'; # renege for the block
2220 *$name = sub { "<FONT COLOR='$name'>@_</FONT>" };
1378 *$name = sub { "<FONT COLOR='$name'>@_</FONT>" };
2221 }
1379 }
22221380
22231381=begin original
22241382
22251383All those functions (red(), blue(), green(), etc.) appear to be separate,
22261384but the real code in the closure actually was compiled only once.
22271385
22281386=end original
22291387
2230これら(red(), blue(), green() など)の関数全ては別々に現れますが、
1388これら(red(), blue(), green()など)の関数全ては別々に現れますが、
22311389クロージャの中の実際のコードは一回だけコンパイルされます。
22321390
22331391=begin original
22341392
2235So, sometimes you might want to use symbolic references to manipulate
1393So, sometimes you might want to use symbolic references to directly
2236the symbol table directly. This doesn't matter for formats, handles, and
1394manipulate the symbol table. This doesn't matter for formats, handles, and
22371395subroutines, because they are always global--you can't use my() on them.
22381396For scalars, arrays, and hashes, though--and usually for subroutines--
22391397you probably only want to use hard references.
22401398
22411399=end original
22421400
22431401シンボルテーブルを直接操作するためにシンボリックリファレンスを
22441402使いたくなることがあるかもしれません。
22451403これには、フォーマット、ハンドル、サブルーチンには関係ありません。
22461404これらは常にグローバルだからです--これらに my() を使うことはできません。
2247おそらく、スカラ、配列、ハッシュのために--そして普通はサブルーチンの
1405おそらく、スカラ、配列、ハッシュのために--そして普通はサブルーチンのために--
2248ために--だけ、ハードリファレンスが必要でしょう。
1406だけ、ハードリファレンスが必要でしょう。
22491407
2250=head2 What does "bad interpreter" mean?
2251
2252("bad interpreter" とはどういう意味ですか?)
2253
2254=begin original
2255
2256(contributed by brian d foy)
2257
2258=end original
2259
2260(brian d foy によって寄贈されました)
2261
2262=begin original
2263
2264The "bad interpreter" message comes from the shell, not perl. The
2265actual message may vary depending on your platform, shell, and locale
2266settings.
2267
2268=end original
2269
2270"bad interpreter" というメッセージは perl ではなく、シェルが出力しています。
2271実際のメッセージはプラットフォーム、シェル、ロケール設定によって
2272様々です。
2273
2274=begin original
2275
2276If you see "bad interpreter - no such file or directory", the first
2277line in your perl script (the "shebang" line) does not contain the
2278right path to perl (or any other program capable of running scripts).
2279Sometimes this happens when you move the script from one machine to
2280another and each machine has a different path to perl--/usr/bin/perl
2281versus /usr/local/bin/perl for instance. It may also indicate
2282that the source machine has CRLF line terminators and the
2283destination machine has LF only: the shell tries to find
2284/usr/bin/perl<CR>, but can't.
2285
2286=end original
2287
2288"bad interpreter - no such file or directory" と表示されたら、perl
2289スクリプトの最初の行 ("#!" 行) に perl (あるいはスクリプトを実行する
2290機能のあるその他のプログラム) への正しいパスが含まれていません。
2291スクリプトをあるマシンから、perl のパスが異なる -- 例えば /usr/bin/perl と
2292/usr/local/bin/perl -- 他のマシンに移動させた場合に時々起こります。
2293これはまた、元のマシンの行終端が CRLF で、移動先のマシンが LF のみの場合にも
2294起こります; シェルが /usr/bin/perl<CR> を探そうとしますが、失敗します。
2295
2296=begin original
2297
2298If you see "bad interpreter: Permission denied", you need to make your
2299script executable.
2300
2301=end original
2302
2303"bad interpreter: Permission denied" と表示されたら、スクリプトを
2304実行可能にする必要があります。
2305
2306=begin original
2307
2308In either case, you should still be able to run the scripts with perl
2309explicitly:
2310
2311=end original
2312
2313どちらの場合でも、明示的に perl でスクリプトを実行できるようにするべきです:
2314
2315 % perl script.pl
2316
2317=begin original
2318
2319If you get a message like "perl: command not found", perl is not in
2320your PATH, which might also mean that the location of perl is not
2321where you expect it so you need to adjust your shebang line.
2322
2323=end original
2324
2325"perl: command not found" のようなメッセージが出た場合、perl が PATH に
2326ありません; つまりおそらくは perl の位置があなたの想定している
2327場所ではないことも意味しているので、#! 行を調整する必要があります。
2328
23291408=head1 AUTHOR AND COPYRIGHT
23301409
2331Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and
1410Copyright (c) 1997-1999 Tom Christiansen and Nathan Torkington.
2332other authors as noted. All rights reserved.
1411All rights reserved.
23331412
2334This documentation is free; you can redistribute it and/or modify it
1413When included as part of the Standard Version of Perl, or as part of
2335under the same terms as Perl itself.
1414its complete documentation whether printed or otherwise, this work
1415may be distributed only under the terms of Perl's Artistic License.
1416Any distribution of this file or derivatives thereof I<outside>
1417of that package require that special arrangements be made with
1418copyright holder.
23361419
23371420Irrespective of its distribution, all code examples in this file
23381421are hereby placed into the public domain. You are permitted and
23391422encouraged to use this code in your own programs for fun
23401423or for profit as you see fit. A simple comment in the code giving
23411424credit would be courteous but is not required.
2342
2343=begin meta
2344
2345Translate: 吉村 寿人 <JAE00534@niftyserve.or.jp>
2346Update: SHIRAKATA Kentaro <argrath@ub32.org> (5.6.1-)
2347Status: completed
2348
2349=end meta