perlsub > 5.42.0 との差分

perlsub 5.42.0 と 5.16.1 の差分

11
2=encoding utf8
2=encoding euc-jp
33
44=head1 NAME
55X<subroutine> X<function>
66
77=begin original
88
9perlsub - Perl subroutines (user-defined functions)
9perlsub - Perl subroutines
1010
1111=end original
1212
13perlsub - Perl のサブルーチン (ユーザー定義関数)
13perlsub - Perl のサブルーチン
1414
1515=head1 SYNOPSIS
1616
1717=begin original
1818
1919To declare subroutines:
2020X<subroutine, declaration> X<sub>
2121
2222=end original
2323
2424サブルーチンを宣言するには:
2525X<subroutine, declaration> X<sub>
2626
2727=begin original
2828
29 sub NAME; # A "forward" declaration.
29 sub NAME; # A "forward" declaration.
30 sub NAME(PROTO); # ditto, but with prototypes
30 sub NAME(PROTO); # ditto, but with prototypes
31 sub NAME : ATTRS; # with attributes
31 sub NAME : ATTRS; # with attributes
32 sub NAME(PROTO) : ATTRS; # with attributes and prototypes
32 sub NAME(PROTO) : ATTRS; # with attributes and prototypes
3333
3434=end original
3535
36 sub NAME; # "先行" 宣言
36 sub NAME; # "先行" 宣言
37 sub NAME(PROTO); # 同上; ただしプロトタイプ付き
37 sub NAME(PROTO); # 同上ただしプロトタイプ付き
38 sub NAME : ATTRS; # 属性付き
38 sub NAME : ATTRS; # 属性付き
39 sub NAME(PROTO) : ATTRS; # 属性とプロトタイプ付き
39 sub NAME(PROTO) : ATTRS; # 属性とプロトタイプ付き
4040
4141=begin original
4242
43 sub NAME BLOCK # A declaration and a definition.
43 sub NAME BLOCK # A declaration and a definition.
44 sub NAME(PROTO) BLOCK # ditto, but with prototypes
44 sub NAME(PROTO) BLOCK # ditto, but with prototypes
45 sub NAME : ATTRS BLOCK # with attributes
45 sub NAME : ATTRS BLOCK # with attributes
46 sub NAME(PROTO) : ATTRS BLOCK # with prototypes and attributes
46 sub NAME(PROTO) : ATTRS BLOCK # with prototypes and attributes
4747
4848=end original
4949
50 sub NAME BLOCK # 宣言と定義
50 sub NAME BLOCK # 宣言と定義
51 sub NAME(PROTO) BLOCK # 同上; ただしプロトタイプ付き
51 sub NAME(PROTO) BLOCK # 同上ただしプロトタイプ付き
52 sub NAME : ATTRS BLOCK # 属性付き
52 sub NAME : ATTRS BLOCK # 属性付き
53 sub NAME(PROTO) : ATTRS BLOCK # プロトタイプと属性付き
53 sub NAME(PROTO) : ATTRS BLOCK # プロトタイプと属性付き
5454
5555=begin original
5656
57 use feature 'signatures';
58 sub NAME(SIG) BLOCK # with signature
59 sub NAME :ATTRS (SIG) BLOCK # with signature, attributes
60 sub NAME :prototype(PROTO) (SIG) BLOCK # with signature, prototype
61
62=end original
63
64 use feature 'signatures';
65 sub NAME(SIG) BLOCK # with signature
66 sub NAME :ATTRS (SIG) BLOCK # with signature, attributes
67 sub NAME :prototype(PROTO) (SIG) BLOCK # with signature, prototype
68
69=begin original
70
7157To define an anonymous subroutine at runtime:
7258X<subroutine, anonymous>
7359
7460=end original
7561
7662実行時に無名サブルーチンを定義するには:
7763X<subroutine, anonymous>
7864
7965=begin original
8066
81 $subref = sub BLOCK; # no proto
67 $subref = sub BLOCK; # no proto
82 $subref = sub (PROTO) BLOCK; # with proto
68 $subref = sub (PROTO) BLOCK; # with proto
83 $subref = sub : ATTRS BLOCK; # with attributes
69 $subref = sub : ATTRS BLOCK; # with attributes
84 $subref = sub (PROTO) : ATTRS BLOCK; # with proto and attributes
70 $subref = sub (PROTO) : ATTRS BLOCK; # with proto and attributes
8571
8672=end original
8773
88 $subref = sub BLOCK; # プロトタイプなし
74 $subref = sub BLOCK; # プロトタイプなし
89 $subref = sub (PROTO) BLOCK; # プロトタイプ付き
75 $subref = sub (PROTO) BLOCK; # プロトタイプ付き
90 $subref = sub : ATTRS BLOCK; # 属性付き
76 $subref = sub : ATTRS BLOCK; # 属性付き
91 $subref = sub (PROTO) : ATTRS BLOCK; # プロトタイプと属性付き
77 $subref = sub (PROTO) : ATTRS BLOCK; # プロトタイプと属性付き
9278
9379=begin original
9480
95 use feature 'signatures';
96 $subref = sub (SIG) BLOCK; # with signature
97 $subref = sub : ATTRS(SIG) BLOCK; # with signature, attributes
98
99=end original
100
101 use feature 'signatures';
102 $subref = sub (SIG) BLOCK; # シグネチャ付き
103 $subref = sub : ATTRS(SIG) BLOCK; # シグネチャと属性付き
104
105=begin original
106
10781To import subroutines:
10882X<import>
10983
11084=end original
11185
11286サブルーチンをインポートするには:
11387X<import>
11488
11589 use MODULE qw(NAME1 NAME2 NAME3);
11690
11791=begin original
11892
11993To call subroutines:
12094X<subroutine, call> X<call>
12195
12296=end original
12397
12498サブルーチンを呼び出すには:
12599X<subroutine, call> X<call>
126100
127101=begin original
128102
129 NAME(LIST); # Regular subroutine call.
103 NAME(LIST); # & is optional with parentheses.
130 NAME LIST; # Parentheses optional if predeclared/imported.
104 NAME LIST; # Parentheses optional if predeclared/imported.
131 &NAME(LIST); # Circumvent prototypes.
105 &NAME(LIST); # Circumvent prototypes.
132 &NAME; # Makes current @_ visible to called subroutine.
106 &NAME; # Makes current @_ visible to called subroutine.
133107
134108=end original
135109
136 NAME(LIST); # 通常のサブルーチン呼び出し
110 NAME(LIST); # かっこが付いているときは & は省略可能
137 NAME LIST; # 予め宣言/インポートされているならかっこは省略可能。
111 NAME LIST; # 予め宣言/インポートされているならかっこは省略可能。
138 &NAME(LIST); # プロトタイプを回避する。
112 &NAME(LIST); # プロトタイプを回避する。
139 &NAME; # 呼び出されたサブルーチンから現在の @_ を可視化する。
113 &NAME; # 呼び出されたサブルーチンから現在の @_ を可視化する。
140114
141115=head1 DESCRIPTION
142116
143117=begin original
144118
145119Like many languages, Perl provides for user-defined subroutines.
146120These may be located anywhere in the main program, loaded in from
147121other files via the C<do>, C<require>, or C<use> keywords, or
148122generated on the fly using C<eval> or anonymous subroutines.
149123You can even call a function indirectly using a variable containing
150124its name or a CODE reference.
151125
152126=end original
153127
154128多くの言語と同様、Perl はユーザー定義のサブルーチンを提供しています。
155129これらのサブルーチンは、メインプログラムのどこにでも置くことができ、
156130C<do>, C<require>, C<use> といったキーワードを使って他のファイルから
157131ロードすることができ、C<eval> や無名サブルーチンを使って
158132生成することもできます。
159133サブルーチンの名前や、コードリファレンスを保持する変数を使って
160134間接的に関数を呼び出すことも可能です。
161135
162136=begin original
163137
164138The Perl model for function call and return values is simple: all
165139functions are passed as parameters one single flat list of scalars, and
166140all functions likewise return to their caller one single flat list of
167141scalars. Any arrays or hashes in these call and return lists will
168142collapse, losing their identities--but you may always use
169143pass-by-reference instead to avoid this. Both call and return lists may
170144contain as many or as few scalar elements as you'd like. (Often a
171145function without an explicit return statement is called a subroutine, but
172146there's really no difference from Perl's perspective.)
173147X<subroutine, parameter> X<parameter>
174148
175149=end original
176150
177151Perl での関数呼び出しと戻り値のモデルは単純です。全ての関数は引数を、
178152平坦で一つのスカラのリストで受け取り、同様に全ての関数は呼び出し元に
179153対して平坦で一つのスカラのりストで返すというものです。
180154これらの呼び出しリストと戻り値リストにある全ての配列とハッシュは、
181155潰されてそのアイデンティティを失います。
182156しかし、これを避けるために常にリファレンスで渡すことができます。
183157呼び出しリストと戻り値リストの両方とも好きなだけの数のスカラを
184158保持することができます(明確な return 文のない関数はしばしばサブルーチンと
185159呼ばれますが、Perl の定義上はこれらの間に何の違いもありません)。
186160
187161=begin original
188162
189In a subroutine that uses signatures (see L</Signatures> below),
163Any arguments passed in show up in the array C<@_>. Therefore, if
190arguments are assigned into lexical variables introduced by the
164you called a function with two arguments, those would be stored in
191signature. In the current implementation of Perl they are also
165C<$_[0]> and C<$_[1]>. The array C<@_> is a local array, but its
192accessible in the C<@_> array in the same way as for non-signature
166elements are aliases for the actual scalar parameters. In particular,
193subroutines, but accessing them in this manner is now discouraged inside
167if an element C<$_[0]> is updated, the corresponding argument is
194such a signature-using subroutine.
168updated (or an error occurs if it is not updatable). If an argument
169is an array or hash element which did not exist when the function
196=end original
170was called, that element is created only when (and if) it is modified
171or a reference to it is taken. (Some earlier versions of Perl
198シグネチャ (後述する L</Signatures> below 参照) を使うサブルーチンでは、
172created the element whether or not the element was assigned to.)
199引数はシグネチャによって導入されるレキシカル変数に代入されます。
173Assigning to the whole array C<@_> removes that aliasing, and does
200現在の Perl の実装では、非シグネチャサブルーチンと同様に
174not update any arguments.
201C<@_> 配列からもアクセス可能ですが、
202この方法にこれらにアクセスするのは、このようなシグネチャを使っている
203サブルーチンでは非推奨です。
204
205=begin original
206
207In a subroutine that does not use signatures, any arguments passed in
208show up in the array C<@_>. Therefore, if you called a function with
209two arguments, those would be stored in C<$_[0]> and C<$_[1]>. The
210array C<@_> is a local array, but its elements are aliases for the
211actual scalar parameters. In particular, if an element C<$_[0]> is
212updated, the corresponding argument is updated (or an error occurs if it
213is not updatable). If an argument is an array or hash element which did
214not exist when the function was called, that element is created only
215when (and if) it is modified or a reference to it is taken. (Some
216earlier versions of Perl created the element whether or not the element
217was assigned to.) Assigning to the whole array C<@_> removes that
218aliasing, and does not update any arguments.
219175X<subroutine, argument> X<argument> X<@_>
220176
221177=end original
222178
223シグネチャを使わないサブルーチンでは、
224179ルーチンに渡されるすべての引数は配列 C<@_> に置かれます。
225180したがって、ある関数を二つの引数を付けて呼び出したならば、
226181その引数は C<$_[0]> と C<$_[1]> に格納されます。
227182配列 C<@_> は local 配列ですが、その要素は実際の
228183スカラパラメータの別名です。
229184たとえば C<$_[0]> が更新された場合、対応する引数が更新されます
230185(更新できない場合にはエラーとなります)。
231186引数が、配列やハッシュの(関数が呼び出された時点では存在してない)
232187要素であった場合、その要素は(対応する別名が)修正されたり
233188リファレンスが取られたときにのみ作成されます。
234189(以前の一部のバージョンの Perl では、この要素は代入が行われようが行われまいが
235190作成されていました。)
236191配列 C<@_> 全体に対する代入は別名を破棄し、何の引数も更新しません。
237192X<subroutine, argument> X<argument> X<@_>
238193
239194=begin original
240195
241When not using signatures, Perl does not otherwise provide a means to
242create named formal parameters. In practice all you do is assign to a
243C<my()> list of these. Variables that aren't declared to be private are
244global variables. For gory details on creating private variables, see
245L</"Private Variables via my()"> and L</"Temporary Values via local()">.
246To create protected environments for a set of functions in a separate
247package (and probably a separate file), see L<perlmod/"Packages">.
248
249=end original
250
251シグネチャを使わない場合、Perl は名前付き仮引数を作る他の手段を
252提供しません。
253実際には、C<my()> にこれらのリストを代入することで行えます。
254プライベートであると宣言されずに使われている変数は全てグローバル変数です。
255プライベート変数に関する詳細はL</"Private Variables via my()"> と
256L</"Temporary Values via local()"> を参照してください。
257パッケージで(おそらくはファイルでも)分けられている関数のセットのための
258保護された環境を作るには L<perlmod/"Packages"> を参照してください。
259
260=begin original
261
262196A C<return> statement may be used to exit a subroutine, optionally
263197specifying the returned value, which will be evaluated in the
264198appropriate context (list, scalar, or void) depending on the context of
265199the subroutine call. If you specify no return value, the subroutine
266200returns an empty list in list context, the undefined value in scalar
267201context, or nothing in void context. If you return one or more
268202aggregates (arrays and hashes), these will be flattened together into
269203one large indistinguishable list.
270204
271205=end original
272206
273207サブルーチンから脱出するために使われた C<return> 文が
274208使われることもありますし、サブルーチン呼び出しのコンテキストによって
275209適切なコンテキスト(リスト、スカラ、無効)で評価される戻り値の指定を
276210省略する事が可能です。
277211もし何の戻り値も指定しなければ、サブルーチンはリストコンテキストにおいては
278212空リストを返し、スカラコンテキストにおいては未定義値を返し、
279213無効コンテキストではなにも返しません。
280214一つまたは複数の集合体 (配列やハッシュ) を返す場合、一つの大きな区別できない
281215リストに平板化されます。
282216
283217=begin original
284218
285219If no C<return> is found and if the last statement is an expression, its
286value is returned. If the last statement is a loop control structure
220value is returned. If the last statement is a loop control structure
287like a C<foreach> or a C<while>, the returned value is unspecified. The
221like a C<foreach> or a C<while>, the returned value is unspecified. The
288222empty sub returns the empty list.
289223X<subroutine, return value> X<return value> X<return>
290224
291225=end original
292226
293227C<return> がなく、最後の文が式だった場合、その値が返されます。
294228最後の文が C<foreach> や C<while> のようなループ制御構造だった場合、
295229返される値は不定です。
296230空のサブルーチンは空リストを返します。
297231X<subroutine, return value> X<return value> X<return>
298232
299233=begin original
300234
235Perl does not have named formal parameters. In practice all you
236do is assign to a C<my()> list of these. Variables that aren't
237declared to be private are global variables. For gory details
238on creating private variables, see L<"Private Variables via my()">
239and L<"Temporary Values via local()">. To create protected
240environments for a set of functions in a separate package (and
241probably a separate file), see L<perlmod/"Packages">.
242X<formal parameter> X<parameter, formal>
243
244=end original
245
246Perlは名前付き仮引数を持っていません。
247C<my()> にこれらのリストを代入することで行えます。
248プライベートであると宣言されずに使われている変数は全てグローバル変数です。
249プライベート変数に関する詳細はL<"Private Variables via my()"> と
250L<"Temporary Values via local()"> を参照してください。
251パッケージで(おそらくはファイルでも)分けられている関数のセットのための
252保護された環境を作るには L<perlmod/"Packages"> を参照してください。
253X<formal parameter> X<parameter, formal>
254
255=begin original
256
301257Example:
302258
303259=end original
304260
305261例:
306262
307263 sub max {
308 my $max = shift(@_);
264 my $max = shift(@_);
309 foreach $foo (@_) {
265 foreach $foo (@_) {
310 $max = $foo if $max < $foo;
266 $max = $foo if $max < $foo;
311 }
267 }
312 return $max;
268 return $max;
313269 }
314270 $bestday = max($mon,$tue,$wed,$thu,$fri);
315271
316272=begin original
317273
318274Example:
319275
320276=end original
321277
322278例:
323279
324280=begin original
325281
326282 # get a line, combining continuation lines
327283 # that start with whitespace
328284
329285=end original
330286
331287 # 行を取り、空白で始まる継続行を連結します
332288
333289 sub get_line {
334 $thisline = $lookahead; # global variables!
290 $thisline = $lookahead; # global variables!
335 LINE: while (defined($lookahead = <STDIN>)) {
291 LINE: while (defined($lookahead = <STDIN>)) {
336 if ($lookahead =~ /^[ \t]/) {
292 if ($lookahead =~ /^[ \t]/) {
337 $thisline .= $lookahead;
293 $thisline .= $lookahead;
338 }
294 }
339 else {
295 else {
340 last LINE;
296 last LINE;
341 }
297 }
342 }
298 }
343 return $thisline;
299 return $thisline;
344300 }
345301
346 $lookahead = <STDIN>; # get first line
302 $lookahead = <STDIN>; # get first line
347303 while (defined($line = get_line())) {
348 ...
304 ...
349305 }
350306
351307=begin original
352308
353309Assigning to a list of private variables to name your arguments:
354310
355311=end original
356312
357313引数に名前を付けるためにプライベート変数のリストに代入する:
358314
359315 sub maybeset {
360 my($key, $value) = @_;
316 my($key, $value) = @_;
361 $Foo{$key} = $value unless $Foo{$key};
317 $Foo{$key} = $value unless $Foo{$key};
362318 }
363319
364320=begin original
365321
366322Because the assignment copies the values, this also has the effect
367323of turning call-by-reference into call-by-value. Otherwise a
368324function is free to do in-place modifications of C<@_> and change
369325its caller's values.
370326X<call-by-reference> X<call-by-value>
371327
372328=end original
373329
374330これは、参照渡しを値渡しにする効果もあります; なぜなら、値のコピーを
375331代入しているからです。
376332このようにしないのであれば、関数は自由に C<@_> の値をその場で
377333書き換えることができ、それはそのまま呼び出し側の値を変更します。
378334X<call-by-reference> X<call-by-value>
379335
380336 upcase_in($v1, $v2); # this changes $v1 and $v2
381337 sub upcase_in {
382 for (@_) { tr/a-z/A-Z/ }
338 for (@_) { tr/a-z/A-Z/ }
383339 }
384340
385341=begin original
386342
387343You aren't allowed to modify constants in this way, of course. If an
388344argument were actually literal and you tried to change it, you'd take a
389345(presumably fatal) exception. For example, this won't work:
390346X<call-by-reference> X<call-by-value>
391347
392348=end original
393349
394350もちろん、このやり方で定数を変更することは許されません。
395351ある引数が実際にはリテラルであった場合にその引数を変更しようとすると、
396352(おそらくは致命的な)例外が引き起こされることになるでしょう。
397353例えば次の例はうまく働きません:
398354X<call-by-reference> X<call-by-value>
399355
400356 upcase_in("frederick");
401357
402358=begin original
403359
404360It would be much safer if the C<upcase_in()> function
405361were written to return a copy of its parameters instead
406362of changing them in place:
407363
408364=end original
409365
410366C<upcase_in()> 関数を安全なものにするには、パラメータそのものを
411367書き換えるのではなくそのコピーを返すように記述するようにします:
412368
413369 ($v3, $v4) = upcase($v1, $v2); # this doesn't change $v1 and $v2
414370 sub upcase {
415 return unless defined wantarray; # void context, do nothing
371 return unless defined wantarray; # void context, do nothing
416 my @parms = @_;
372 my @parms = @_;
417 for (@parms) { tr/a-z/A-Z/ }
373 for (@parms) { tr/a-z/A-Z/ }
418 return wantarray ? @parms : $parms[0];
374 return wantarray ? @parms : $parms[0];
419375 }
420376
421377=begin original
422378
423379Notice how this (unprototyped) function doesn't care whether it was
424380passed real scalars or arrays. Perl sees all arguments as one big,
425381long, flat parameter list in C<@_>. This is one area where
426382Perl's simple argument-passing style shines. The C<upcase()>
427383function would work perfectly well without changing the C<upcase()>
428384definition even if we fed it things like this:
429385
430386=end original
431387
432388この(プロトタイプがついていない)関数が自分に対して本当のスカラが
433389渡されたのか配列が渡されたのかを気にしていないということに注意してください。
434390Perl は一つの巨大な平坦な(リストの中にリストが含まれることはない、
435391ということ) C<@_> パラメータリストとして全ての引数を見るのです。
436392これは Perl の単純な引数渡しの形式のやり方の一つです。
437393この C<upcase()> 関数は、以下のような呼び出しをした場合でも C<upcase()> の
438394定義を変更することなく完璧に動作します:
439395
440396 @newlist = upcase(@list1, @list2);
441397 @newlist = upcase( split /:/, $var );
442398
443399=begin original
444400
445401Do not, however, be tempted to do this:
446402
447403=end original
448404
449405ただし、以下のような呼び出しをやろうとしてはいけません:
450406
451 (@x, @y) = upcase(@list1, @list2);
407 (@a, @b) = upcase(@list1, @list2);
452408
453409=begin original
454410
455411Like the flattened incoming parameter list, the return list is also
456412flattened on return. So all you have managed to do here is stored
457everything in C<@x> and made C<@y> empty. See
413everything in C<@a> and made C<@b> empty. See
458L</Pass by Reference> for alternatives.
414L<Pass by Reference> for alternatives.
459415
460416=end original
461417
462418関数に渡される引数リストは平坦なリストであるのと同様、戻り値のリストも
463419また平坦なリストです。
464ですから、関数が返した全ての要素は C<@x> に格納され、C<@y> は
420ですから、関数が返した全ての要素は C<@a> に格納され、C<@b> は
465421空になります。
466別のやり方については L</Pass by Reference> を参照してください。
422別のやり方については L</"Pass by Reference"> を参照してください。
467423
468424=begin original
469425
470426A subroutine may be called using an explicit C<&> prefix. The
471427C<&> is optional in modern Perl, as are parentheses if the
472428subroutine has been predeclared. The C<&> is I<not> optional
473429when just naming the subroutine, such as when it's used as
474430an argument to defined() or undef(). Nor is it optional when you
475431want to do an indirect subroutine call with a subroutine name or
476432reference using the C<&$subref()> or C<&{$subref}()> constructs,
477433although the C<< $subref->() >> notation solves that problem.
478434See L<perlref> for more about all that.
479435X<&>
480436
481437=end original
482438
483439サブルーチンは、明示的な C<&> というプリフィックスを付けて呼び出すことが
484440できます。
485441最近の Perl では C<&> は省略可能であり、サブルーチンがあらかじめ
486442宣言されている場合には括弧も省略できます。
487443defined() や undef() の引数として使ったような、単なる名前付き
488サブルーチンであるときの C<&> は I<省略可能ではありません>。
444サブルーチンであるときの C<&> は B<省略可能ではありません>。
489445C<&$subref()> や C<&{$subref}()> のような、サブルーチンの名前や
490446リファレンスを使った間接的なサブルーン呼び出しを行いたいたいときにも
491447C<&> は省略することはできません; 但し C<< $subref->() >> の記法が問題を
492448解決します。
493449詳しくは L<perlref> を参照してください。
494450X<&>
495451
496452=begin original
497453
498454Subroutines may be called recursively. If a subroutine is called
499455using the C<&> form, the argument list is optional, and if omitted,
500456no C<@_> array is set up for the subroutine: the C<@_> array at the
501457time of the call is visible to subroutine instead. This is an
502458efficiency mechanism that new users may wish to avoid.
503459X<recursion>
504460
505461=end original
506462
507463サブルーチンは再帰的に呼び出すこともできます。
508464あるサブルーチンが C<&> 付きで呼び出されたなら、引数リストは省略可能で、
509465もし省略されたなら、そのサブルーチンに対して C<@_> 配列は設定されません:
510466代わりに呼び出し時の C<@_> 配列がサブルーチンに対して可視となります。
511467これは新しいユーザーが避けたいと思う効果的なメカニズムです。
512468X<recursion>
513469
514470=begin original
515471
516 &foo(1,2,3); # pass three arguments
472 &foo(1,2,3); # pass three arguments
517 foo(1,2,3); # the same
473 foo(1,2,3); # the same
518474
519475=end original
520476
521 &foo(1,2,3); # 三つの引数を渡す
477 &foo(1,2,3); # 三つの引数を渡す
522 foo(1,2,3); # 上と同じ
478 foo(1,2,3); # 上と同じ
523479
524480=begin original
525481
526 foo(); # pass an empty argument list
482 foo(); # pass a null list
527 &foo(); # the same
483 &foo(); # the same
528484
529485=end original
530486
531 foo(); # 空引数リストを渡す
487 foo(); # 空リストを渡す
532 &foo(); # 上と同じ
488 &foo(); # 上と同じ
533489
534490=begin original
535491
536 &foo; # foo() gets current args, like foo(@_)!
492 &foo; # foo() get current args, like foo(@_) !!
537 use strict 'subs';
493 foo; # like foo() IFF sub foo predeclared, else "foo"
538 foo; # like foo() iff sub foo predeclared, else
539 # a compile-time error
540 no strict 'subs';
541 foo; # like foo() iff sub foo predeclared, else
542 # a literal string "foo"
543494
544495=end original
545496
546 &foo; # foo() は foo(@_) と同様現在の引数を取る!
497 &foo; # foo() は foo(@_) と同様現在の引数を取る!!
547 use strict 'subs';
498 foo; # サブルーチン foo が予め定義されている場合に限り
548 foo; # サブルーチン foo が予め定義さている場合に限り
499 # foo() と同様、そ以外では "foo"
549 # foo() と同様、それ以外ではコンパイル時エラー
550 no strict 'subs';
551 foo; # サブルーチン foo が予め定義されている場合に限り
552 # foo() と同様、それ以外では文字列リテラル "foo"
553500
554501=begin original
555502
556503Not only does the C<&> form make the argument list optional, it also
557504disables any prototype checking on arguments you do provide. This
558505is partly for historical reasons, and partly for having a convenient way
559506to cheat if you know what you're doing. See L</Prototypes> below.
560507X<&>
561508
562509=end original
563510
564511C<&> 形式は引数リストを省略可能にするばかりでなく、与えられた引数に
565512対するすべてのプロトタイプチェックも無効にします。
566513これは一部には歴史的な理由であり、一部にはあなたが自分の行っている動作を
567514わかっているときにうまくごまかしを行う便利な方法を残しておくためです。
568515後に出てくる L</Prototypes> を参照してください。
569516X<&>
570517
571518=begin original
572519
573520Since Perl 5.16.0, the C<__SUB__> token is available under C<use feature
574'current_sub'> and C<use v5.16>. It will evaluate to a reference to the
521'current_sub'> and C<use 5.16.0>. It will evaluate to a reference to the
575522currently-running sub, which allows for recursive calls without knowing
576523your subroutine's name.
577524
578525=end original
579526
580Perl 5.16.0 から、C<use feature 'current_sub'> または C<use v5.16> が有効の
527Perl 5.16.0 から、C<use feature 'current_sub'> または C<use 5.16.0> が有効の
581528場合は C<__SUB__> トークンが利用可能です。
582529これは現在実行しているサブルーチンへのリファレンスを評価するので、
583530現在のサブルーチン名を知ることなく再帰呼び出しができるようになります。
584531
585 use v5.16;
532 use 5.16.0;
586533 my $factorial = sub {
587 my ($x) = @_;
534 my ($x) = @_;
588 return 1 if $x == 1;
535 return 1 if $x == 1;
589 return($x * __SUB__->( $x - 1 ) );
536 return($x * __SUB__->( $x - 1 ) );
590537 };
591538
592539=begin original
593540
594The behavior of C<__SUB__> within a regex code block (such as C</(?{...})/>)
595is subject to change.
596
597=end original
598
599(C</(?{...})/> のような) 正規表現コードブロック中の C<__SUB__> の振る舞いは
600変更されるかもしれません。
601
602=begin original
603
604541Subroutines whose names are in all upper case are reserved to the Perl
605542core, as are modules whose names are in all lower case. A subroutine in
606543all capitals is a loosely-held convention meaning it will be called
607544indirectly by the run-time system itself, usually due to a triggered event.
608Subroutines whose name start with a left parenthesis are also reserved the
545Subroutines that do special, pre-defined things include C<AUTOLOAD>, C<CLONE>,
609same way. The following is a list of some subroutines that currently do
546C<DESTROY> plus all functions mentioned in L<perltie> and L<PerlIO::via>.
610special, pre-defined things.
611547
612548=end original
613549
614名前が全て大文字であるサブルーチンは、名前が全て小文字のモジュール名が
550名前が全て大文字であるサブルーチンは、
615予約されているのと同じようにPerl のコアで予約されています。
551名前が全て小文字のモジュール名が (訳注: pragma 用として) 予約されているのと同じように
616実行時にシステム自身によって (通常はイベントをトリガーとして) 間接的に
552Perl のコアで予約されています。実行時にシステム自身によって
617呼び出されるサブルーチンは、名前を全て大文字で書くのがしきたりです。
553(通常はイベントをトリガーとして) 間接的に呼び出されるサブルーチンは、
618名前が左かっこ始まるようなサブルーチンも同様に予約されています。
554名前を全て大文字で書くのしきたりです。
619以下は現在のところ特殊で事前に定義されていることがあるサブルーチンの一覧です。
555特殊で、あらかじめ決められていることをするサブルーチンは、
556C<AUTOLOAD>, C<CLONE>, C<DESTROY> に、L<perltie> と L<PerlIO::via> で
557説明されている関数全てを加えたものです。
620558
621=over
622
623=item documented later in this document
624
625(この文書で後述するもの)
626
627C<AUTOLOAD>
628
629=item documented in L<perlmod>
630
631(L<perlmod> に記述しているもの)
632
633C<CLONE>, C<CLONE_SKIP>
634
635=item documented in L<perlobj>
636
637(L<perlobj> に記述しているもの)
638
639C<DESTROY>, C<DOES>
640
641=item documented in L<perltie>
642
643(L<perltie> に記述しているもの)
644
645C<BINMODE>, C<CLEAR>, C<CLOSE>, C<DELETE>, C<DESTROY>, C<EOF>, C<EXISTS>,
646C<EXTEND>, C<FETCH>, C<FETCHSIZE>, C<FILENO>, C<FIRSTKEY>, C<GETC>,
647C<NEXTKEY>, C<OPEN>, C<POP>, C<PRINT>, C<PRINTF>, C<PUSH>, C<READ>,
648C<READLINE>, C<SCALAR>, C<SEEK>, C<SHIFT>, C<SPLICE>, C<STORE>,
649C<STORESIZE>, C<TELL>, C<TIEARRAY>, C<TIEHANDLE>, C<TIEHASH>,
650C<TIESCALAR>, C<UNSHIFT>, C<UNTIE>, C<WRITE>
651
652=item documented in L<PerlIO::via>
653
654(L<PerlIO::via> に記述しているもの)
655
656C<BINMODE>, C<CLEARERR>, C<CLOSE>, C<EOF>, C<ERROR>, C<FDOPEN>, C<FILENO>,
657C<FILL>, C<FLUSH>, C<OPEN>, C<POPPED>, C<PUSHED>, C<READ>, C<SEEK>,
658C<SETLINEBUF>, C<SYSOPEN>, C<TELL>, C<UNREAD>, C<UTF8>, C<WRITE>
659
660=item documented in L<perlfunc>
661
662(L<perlfunc> に記述しているもの)
663
664L<< C<import>|perlfunc/use >>, L<< C<unimport>|perlfunc/use >>,
665L<< C<INC>|perlfunc/require >>
666
667=item documented in L<UNIVERSAL>
668
669(L<UNIVERSAL> に記述しているもの)
670
671C<VERSION>
672
673=item documented in L<perldebguts>
674
675(L<perldebguts> に記述しているもの)
676
677C<DB::DB>, C<DB::sub>, C<DB::lsub>, C<DB::goto>, C<DB::postponed>
678
679=item undocumented, used internally by the L<overload> feature
680
681(文書化されておらず、L<overload> 機能によって内部で使われているもの)
682
683559=begin original
684560
685any starting with C<(>
686
687=end original
688
689C<(> で始まるもの全て
690
691=back
692
693=begin original
694
695561The C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT> and C<END> subroutines
696562are not so much subroutines as named special code blocks, of which you
697563can have more than one in a package, and which you can B<not> call
698564explicitly. See L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END">
699565
700566=end original
701567
702C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT>, C<END> サブルーチンは
568The C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT>, C<END> サブルーチンは
703569サブルーチンというよりは特殊コードブロックで、その中でも一つのパッケージに
704570複数作ることができ、明示的には B<呼び出せません> 。
705571L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END"> を参照してください。
706572
707=head2 Signatures
708
709(シグネチャ)
710
711X<formal parameter> X<parameter, formal>
712
713=begin original
714
715Perl has a facility to allow a subroutine's formal parameters to be
716declared by special syntax, separate from the procedural code of the
717subroutine body. The formal parameter list is known as a I<signature>.
718
719=end original
720
721Perl は、サブルーチン本体の手続き的コードと分離された特殊な文法を
722宣言することで、サブルーチンの仮引数を指定できる機能を持ちます。
723仮引数リストは I<シグネチャ> (signature) として知られます。
724
725=begin original
726
727This facility must be enabled before it can be used. It is enabled
728automatically by a C<use v5.36> (or higher) declaration, or more
729directly by C<use feature 'signatures'>, in the current scope.
730
731=end original
732
733この機能は、使われる前に有効にされなければなりません。
734これは C<use v5.36> (またはそれ以上) 宣言で自動的に、
735あるいはより直接的に現在のスコープ内で C<use feature 'signatures'> と
736することで有効になります。
737
738=begin original
739
740The signature is part of a subroutine's body. Normally the body of a
741subroutine is simply a braced block of code, but when using a signature,
742the signature is a parenthesised list that goes immediately before the
743block, after any name or attributes.
744
745=end original
746
747シグネチャはサブルーチンの本体の一部です。
748通常サブルーチンの本体は単に中かっこのブロックのコードですが、
749シグネチャを使うとき、シグネチャはブロックの直前、
750なんらかの名前や属性の直後に置かれたかっこつきリストです。
751
752=begin original
753
754For example,
755
756=end original
757
758例えば、
759
760 sub foo :lvalue ($x, $y = 1, @z) { .... }
761
762=begin original
763
764The signature declares lexical variables that are
765in scope for the block. When the subroutine is called, the signature
766takes control first. It populates the signature variables from the
767list of arguments that were passed. If the argument list doesn't meet
768the requirements of the signature, then it will throw an exception.
769When the signature processing is complete, control passes to the block.
770
771=end original
772
773シグネチャはそのブロックのスコープのレキシカル変数を宣言します。
774サブルーチンが呼び出されるとき、シグネチャが最初に制御します。
775渡された引数リストからシグネチャ変数を作ります。
776引数リストがシグネチャの要求に一致しない場合、例外が投げられます。
777シグネチャ処理が完了したとき、制御はブロックに移ります。
778
779=begin original
780
781Positional parameters are handled by simply naming scalar variables in
782the signature. For example,
783
784=end original
785
786位置パラメータは単にシグネチャの名前付きスカラ変数で扱われます。
787例えば、
788
789 sub foo ($left, $right) {
790 return $left + $right;
791 }
792
793=begin original
794
795takes two positional parameters, which must be filled at runtime by
796two arguments. By default the parameters are mandatory, and it is
797not permitted to pass more arguments than expected. So the above is
798equivalent to
799
800=end original
801
802これは二つの位置パラメータを持ち、二つの引数によって実行時に
803埋められなければなりません。
804デフォルトではパラメータは必須で、想定以上の引数を渡すことは許されません。
805従って前述のものは以下と等価です
806
807 sub foo {
808 die "Too many arguments for subroutine" unless @_ <= 2;
809 die "Too few arguments for subroutine" unless @_ >= 2;
810 my $left = $_[0];
811 my $right = $_[1];
812 return $left + $right;
813 }
814
815=begin original
816
817An argument can be ignored by omitting the main part of the name from
818a parameter declaration, leaving just a bare C<$> sigil. For example,
819
820=end original
821
822引数は、パラメータ宣言の名前のメイン部分を省略して裸の C<$> 印だけに
823することで無視できます。
824例えば、
825
826 sub foo ($first, $, $third) {
827 return "first=$first, third=$third";
828 }
829
830=begin original
831
832Although the ignored argument doesn't go into a variable, it is still
833mandatory for the caller to pass it.
834
835=end original
836
837無視された引数は変数には入りませんが、呼び出し元から渡されるときには
838必須のままです。
839
840=begin original
841
842A positional parameter is made optional by giving a default value,
843separated from the parameter name by C<=>:
844
845=end original
846
847位置パラメータは、パラメータ名と C<=> で分けられたデフォルト値を与えることで
848オプションにできます:
849
850 sub foo ($left, $right = 0) {
851 return $left + $right;
852 }
853
854=begin original
855
856The above subroutine may be called with either one or two arguments.
857The default value expression is evaluated when the subroutine is called,
858so it may provide different default values for different calls. It is
859only evaluated if the argument was actually omitted from the call.
860For example,
861
862=end original
863
864前述のサブルーチンは 1 引数か 2 引数で呼び出せます。
865デフォルト値式はサブルーチンが呼び出されるときに評価されます; 従って
866呼び出し毎に異なったデフォルト値を提供できます。
867これは呼び出しで引数が実際に省略されたときにのみ評価されます。
868例えば、
869
870 my $auto_id = 0;
871 sub foo ($thing, $id = $auto_id++) {
872 print "$thing has ID $id";
873 }
874
875=begin original
876
877automatically assigns distinct sequential IDs to things for which no
878ID was supplied by the caller. A default value expression may also
879refer to parameters earlier in the signature, making the default for
880one parameter vary according to the earlier parameters. For example,
881
882=end original
883
884これは、呼び出し元から ID が指定されなかった場合、ユニークな連番 ID が
885自動的に代入されます。
886デフォルト値式はシグネチャ内で前にあるパラメータを参照することもでき、
887前のパラメータによって異なったパラメータのデフォルトを作ります。
888例えば、
889
890 sub foo ($first_name, $surname, $nickname = $first_name) {
891 print "$first_name $surname is known as \"$nickname\"";
892 }
893
894=begin original
895
896Since Perl 5.38, a default value expression can also be written using the
897C<//=> operator, where it will be evaluated and used if the caller omitted
898a value or the value provided was C<undef>.
899
900=end original
901
902Perl 5.38 から、デフォルト値式は、C<//=> 演算子を使って書くこともできます;
903これは、呼び出し元が値を省略するか、提供された値が
904C<undef> の時に評価されて使われます。
905
906 sub foo ($name //= "world") {
907 print "Hello, $name";
908 }
909
910 foo(undef); # will print "Hello, world"
911
912=begin original
913
914Similarly since Perl 5.38, the C<||=> operator can be used to provide a
915default expression to be used whenever the caller provided a false value
916(and remember that a missing or C<undef> value are also false).
917
918=end original
919
920同様に Perl 5.38 から、C<||=> 演算子は、呼び出し元が何らかの偽の値を
921提供したときに使われるデフォルト式を提供するために使われます
922(値がなかったり C<undef> 値の場合も偽であることを忘れないでください)。
923
924 sub foo ($x ||= 10) {
925 return 5 + $x;
926 }
927
928=begin original
929
930An optional parameter can be nameless just like a mandatory parameter.
931For example,
932
933=end original
934
935オプションのパラメータは必須のパラメータと同様に名前なしにできます。
936例えば、
937
938 sub foo ($thing, $ = 1) {
939 print $thing;
940 }
941
942=begin original
943
944The parameter's default value will still be evaluated if the corresponding
945argument isn't supplied, even though the value won't be stored anywhere.
946This is in case evaluating it has important side effects. However, it
947will be evaluated in void context, so if it doesn't have side effects
948and is not trivial it will generate a warning if the "void" warning
949category is enabled. If a nameless optional parameter's default value
950is not important, it may be omitted just as the parameter's name was:
951
952=end original
953
954パラメータのデフォルト値は対応する引数が指定されなくても評価されますが、
955その値はどこにも保管されません。
956これは、評価が重要な副作用を持つ場合です。
957しかし、これは無効コンテキストで評価されるので、副作用がなくて
958ありふれていなければ、"void" 警告カテゴリが有効の場合は警告が生成されます。
959名前なしオプションパラメータのデフォルト値が重要でないなら、パラメータの名前と
960同じように省略できます:
961
962 sub foo ($thing, $=) {
963 print $thing;
964 }
965
966=begin original
967
968Optional positional parameters must come after all mandatory positional
969parameters. (If there are no mandatory positional parameters then the
970optional positional parameters can be the first thing in the signature.)
971If there are multiple optional positional parameters and not enough
972arguments are supplied to fill them all, they will be filled from left
973to right.
974
975=end original
976
977オプション位置パラメータは全ての必須位置パラメータの
978後ろでなければなりません。
979(必須位置パラメータがない場合は、オプション位置パラメータをシグネチャの
980最初の位置に置けます。)
981複数のオプション位置パラメータがあって全てのパラメータを設定するのに十分な
982引数が供給されなかった場合、左から右に設定されます。
983
984=begin original
985
986After positional parameters, additional arguments may be captured in a
987slurpy parameter. The simplest form of this is just an array variable:
988
989=end original
990
991位置パラメータの後、追加の引数は吸い込みパラメータに捕捉されます。
992これの最も単純な形式は単なる配列変数です:
993
994 sub foo ($filter, @inputs) {
995 print $filter->($_) foreach @inputs;
996 }
997
998=begin original
999
1000With a slurpy parameter in the signature, there is no upper limit on how
1001many arguments may be passed. A slurpy array parameter may be nameless
1002just like a positional parameter, in which case its only effect is to
1003turn off the argument limit that would otherwise apply:
1004
1005=end original
1006
1007シグネチャで吸い込みパラメータがある場合、渡せる引数の数に上限はありません。
1008吸い込み配列パラメータは位置パラメータと同様に名前なしにでき、この場合は
1009その他の場合で適用される引数制限をオフにする効果のみがあります:
1010
1011 sub foo ($thing, @) {
1012 print $thing;
1013 }
1014
1015=begin original
1016
1017A slurpy parameter may instead be a hash, in which case the arguments
1018available to it are interpreted as alternating keys and values.
1019There must be as many keys as values: if there is an odd argument then
1020an exception will be thrown. Keys will be stringified, and if there are
1021duplicates then the later instance takes precedence over the earlier,
1022as with standard hash construction.
1023
1024=end original
1025
1026吸い込みパラメータは代わりにハッシュにすることもでき、その場合利用可能な
1027引数は交互にキーと値として解釈されます。
1028キーと値の数は同じでなければなりません: 引数が奇数だと例外が投げられます。
1029キーは文字列化され、重複があると、通常のハッシュの構築と同じように、
1030後から指定したものが先に指定したものを上書きします。
1031
1032 sub foo ($filter, %inputs) {
1033 print $filter->($_, $inputs{$_}) foreach sort keys %inputs;
1034 }
1035
1036=begin original
1037
1038A slurpy hash parameter may be nameless just like other kinds of
1039parameter. It still insists that the number of arguments available to
1040it be even, even though they're not being put into a variable.
1041
1042=end original
1043
1044吸い込みハッシュパラメータは他の種類のパラメータと同様に名前なしにできます。
1045変数に代入されなくても、利用できる引数の数が偶数であるという必要はあります。
1046
1047 sub foo ($thing, %) {
1048 print $thing;
1049 }
1050
1051=begin original
1052
1053A slurpy parameter, either array or hash, must be the last thing in the
1054signature. It may follow mandatory and optional positional parameters;
1055it may also be the only thing in the signature. Slurpy parameters cannot
1056have default values: if no arguments are supplied for them then you get
1057an empty array or empty hash.
1058
1059=end original
1060
1061吸い込みパラメータは、配列でもハッシュでも、シグネチャの
1062最後でなければなりません。
1063必須とオプションの位置パラメータに引き続くことができます; シグネチャの唯一の
1064要素でもかまいません。
1065吸い込みパラメータはデフォルト値を持つことはできません: 引数が指定されないと
1066空配列や空ハッシュを得ます。
1067
1068=begin original
1069
1070A signature may be entirely empty, in which case all it does is check
1071that the caller passed no arguments:
1072
1073=end original
1074
1075シグネチャは完全に空にすることもできます; この場合、呼び出し側が引数を
1076渡していないことだけをチェックします:
1077
1078 sub foo () {
1079 return 123;
1080 }
1081
1082=begin original
1083
1084Prior to Perl 5.36 these were considered experimental, and emitted a
1085warning in the C<experimental::signatures> category. From Perl 5.36
1086onwards this no longer happens, though the warning category still exists
1087for back-compatibility with code that attempts to disable it with a
1088statement such as:
1089
1090=end original
1091
1092Perl 5.36 より前では、これらは実験的と考えられていて、
1093C<experimental::signatures> カテゴリの警告を出力していました。
1094Perl 5.36 以降は、もはやこれはおきませんが、
1095次のような文でこれを無効にしようとするコードとの後方互換性のために、
1096警告カテゴリは存在したままです:
1097
1098 no warnings 'experimental::signatures';
1099
1100=begin original
1101
1102In the current Perl implementation, when using a signature the arguments
1103are still also available in the special array variable C<@_>. However,
1104accessing them via this array is now discouraged, and should not be
1105relied upon in newly-written code as this ability may change in a future
1106version. Code that attempts to access the C<@_> array will produce
1107warnings in the C<experimental::args_array_with_signatures> category when
1108compiled:
1109
1110=end original
1111
1112現在の perl の実装では、シグネチャを使うときも、
1113特殊配列変数 C<@_> にも入ります。
1114しかし、この配列を通してこれらにアクセするのは現在非推奨であり、
1115この機能は将来のバージョンで変わるかもしれないので、
1116新しく書かれるコードはこれに依存するべきではありません。
1117C<@_> 配列にアクセスしようとするコードは、
1118コンパイル時に C<experimental::args_array_with_signatures> カテゴリの
1119警告を発生させます:
1120
1121 sub f ($x) {
1122 # This line emits the warning seen below
1123 print "Arguments are @_";
1124 }
1125
1126Z<>
1127
1128 Use of @_ in join or string with signatured subroutine is
1129 experimental at ...
1130
1131=begin original
1132
1133There is a difference between the two ways of accessing the arguments:
1134C<@_> I<aliases> the arguments, but the signature variables get
1135I<copies> of the arguments. So writing to a signature variable only
1136changes that variable, and has no effect on the caller's variables, but
1137writing to an element of C<@_> modifies whatever the caller used to
1138supply that argument.
1139
1140=end original
1141
1142引数への二つのアクセス方法には違いがあります:
1143C<@_> は引数の I<別名> ですが、
1144シグネチャ変数は引数の I<コピー> です。
1145従って、シグネチャ変数に書き込むとその変数だけが変更され、呼び出し元の
1146変数には影響しませんが、C<@_> の要素に書き込むと引数を指定した呼び出し元が
1147使ったものが修正されます。
1148
1149=begin original
1150
1151There is a potential syntactic ambiguity between signatures and prototypes
1152(see L</Prototypes>), because both start with an opening parenthesis and
1153both can appear in some of the same places, such as just after the name
1154in a subroutine declaration. For historical reasons, when signatures
1155are not enabled, any opening parenthesis in such a context will trigger
1156very forgiving prototype parsing. Most signatures will be interpreted
1157as prototypes in those circumstances, but won't be valid prototypes.
1158(A valid prototype cannot contain any alphabetic character.) This will
1159lead to somewhat confusing error messages.
1160
1161=end original
1162
1163シグネチャとプロトタイプ(L</Prototypes> 参照)の間には潜在的に文法的な
1164あいまいさがあります; 両方とも開きかっこで始まり、サブルーチン宣言の名前の
1165直後といった同じ場所に現れるからです。
1166歴史的な理由により、シグネチャが有効でない場合、このようなコンテキストでの
1167あらゆる開きかっこはとても寛容なプロトタイプのパースを引き起こします。
1168ほとんどのシグネチャはこの状態ではプロトタイプとして解釈されますが、
1169正当なプロトタイプではありません。
1170(正当なプロトタイプは英数字を含むことができません。)
1171これは少し混乱したエラーメッセージを引き起こします。
1172
1173=begin original
1174
1175To avoid ambiguity, when signatures are enabled the special syntax
1176for prototypes is disabled. There is no attempt to guess whether a
1177parenthesised group was intended to be a prototype or a signature.
1178To give a subroutine a prototype under these circumstances, use a
1179L<prototype attribute|attributes/Built-in Attributes>. For example,
1180
1181=end original
1182
1183曖昧さを避けるために、シグネチャが有効の時はプロトタイプのための特殊文法は
1184無効になります。
1185かっこのグループがプロトタイプかシグネチャかを推測しようとはしません。
1186この状態でサブルーチンにプロトタイプを指定するには、
1187L<プロトタイプ属性|attributes/Built-in Attributes> を使ってください。
1188例えば、
1189
1190 sub foo :prototype($) { $_[0] }
1191
1192=begin original
1193
1194It is entirely possible for a subroutine to have both a prototype and
1195a signature. They do different jobs: the prototype affects compilation
1196of calls to the subroutine, and the signature puts argument values into
1197lexical variables at runtime. You can therefore write
1198
1199=end original
1200
1201プロトタイプとシグネチャの両方を持ったサブルーチンは完全に可能です。
1202これらは異なった仕事をします: プロトタイプはサブルーチン呼び出しのコンパイルに
1203影響を与え、シグネチャは実行時に引数の値をレキシカル変数に設定します。
1204従って、このように書けます
1205
1206 sub foo :prototype($$) ($left, $right) {
1207 return $left + $right;
1208 }
1209
1210=begin original
1211
1212The prototype attribute, and any other attributes, must come before
1213the signature. The signature always immediately precedes the block of
1214the subroutine's body.
1215
1216=end original
1217
1218プロトタイプ属性、およびその他の属性はシグネチャの前に来なければなりません。
1219シグネチャは常にサブルーチンの本体のブロックの直前です。
1220
1221573=head2 Private Variables via my()
1222574X<my> X<variable, lexical> X<lexical> X<lexical variable> X<scope, lexical>
1223575X<lexical scope> X<attributes, my>
1224576
1225577(my() によるプライベート変数)
1226578
1227579=begin original
1228580
1229581Synopsis:
1230582
1231583=end original
1232584
1233585概要:
1234586
1235 my $foo; # declare $foo lexically local
587 my $foo; # declare $foo lexically local
1236 my (@wid, %get); # declare list of variables local
588 my (@wid, %get); # declare list of variables local
1237 my $foo = "flurp"; # declare $foo lexical, and init it
589 my $foo = "flurp"; # declare $foo lexical, and init it
1238 my @oof = @bar; # declare @oof lexical, and init it
590 my @oof = @bar; # declare @oof lexical, and init it
1239 my $x : Foo = $y; # similar, with an attribute applied
591 my $x : Foo = $y; # similar, with an attribute applied
1240592
1241593=begin original
1242594
1243595B<WARNING>: The use of attribute lists on C<my> declarations is still
1244596evolving. The current semantics and interface are subject to change.
1245597See L<attributes> and L<Attribute::Handlers>.
1246598
1247599=end original
1248600
1249601B<警告>: C<my> 定義での属性リストの使用はいまだ改良の途中です。
1250602現在の文法とインターフェースは変更される可能性があります。
1251603L<attributes> と L<Attribute::Handlers> を参照してください。
1252604
1253605=begin original
1254606
1255607The C<my> operator declares the listed variables to be lexically
1256confined to the enclosing block, conditional
608confined to the enclosing block, conditional (C<if/unless/elsif/else>),
1257(C<if>/C<unless>/C<elsif>/C<else>), loop
609loop (C<for/foreach/while/until/continue>), subroutine, C<eval>,
1258(C<for>/C<foreach>/C<while>/C<until>/C<continue>), subroutine, C<eval>,
610or C<do/require/use>'d file. If more than one value is listed, the
1259or C<do>/C<require>/C<use>'d file. If more than one value is listed, the
1260611list must be placed in parentheses. All listed elements must be
1261612legal lvalues. Only alphanumeric identifiers may be lexically
1262613scoped--magical built-ins like C<$/> must currently be C<local>ized
1263with C<local> instead to limit their scope dynamically.
614with C<local> instead.
1264615
1265616=end original
1266617
1267C<my> 演算子は、それを囲んでいるブロック、条件文
618C<my> 演算子は、それを囲んでいるブロック、条件文 (C<if/unless/elsif/else>)、
1268(C<if>/C<unless>/C<elsif>/C<else>)ループ
619ループ(C<for/foreach/while/until/continue>)、サブルーチン、C<eval>、
1269(C<for>/C<foreach>/C<while>/C<until>/C<continue>)、サブーチン、C<eval>、
620あるいは C<do/require/use> されたファイにレキシカルに閉じ込められる
1270あるいは C<do>/C<require>/C<use> されたファイルにレキシカルに閉じ込められる
1271621変数を定義します。二つ以上リストアップされている場合には、そのリストは
1272622括弧でくくられていなければなりません。
1273623すべてのリスト要素は正しい左辺値でなければなりません。
1274C<$/> のような組み込み変数が現時点では
624C<$/> のような組み込み変数が現時点では C<local> で
1275スコープを動的に制限する代わりに C<local> で
1276625B<局所化> されなければならないのに対し、
1277アルファベットと数字による識別子はレキシカルでマジカルな
626アルファベットと数字による識別子はレキシカルでマジカルなスコープになります。
1278スコープになります。
1279627
1280628=begin original
1281629
1282Unlike global or package variables localized by the C<local> operator,
630Unlike dynamic variables created by the C<local> operator, lexical
1283lexical variables declared with C<my> are totally hidden from the outside
631variables declared with C<my> are totally hidden from the outside
1284world, including any called subroutines. This is true if it's the same
632world, including any called subroutines. This is true if it's the
1285subroutine called from itself or elsewhere--every call gets its own copy.
633same subroutine called from itself or elsewhere--every call gets
634its own copy.
1286635X<local>
1287636
1288637=end original
1289638
1290C<local> 文によってローカル化されたグローバルまたはパッケージ変数とは異なり、
639C<local> 文によって生成される動的変数とは異なり、C<my> を使って
1291C<my> を使って
1292640宣言されたレキシカル変数はそれを呼び出したサブルーチンも含め、外側の
1293641世界からは秘匿されます。
1294642自分自身が同じサブルーチンを呼んだ場合でさえそうです--個々の呼び出しは
1295643それぞれのコピーを所有します。
1296644X<local>
1297645
1298646=begin original
1299647
1300648This doesn't mean that a C<my> variable declared in a statically
1301649enclosing lexical scope would be invisible. Only dynamic scopes
1302650are cut off. For example, the C<bumpx()> function below has access
1303651to the lexical $x variable because both the C<my> and the C<sub>
1304652occurred at the same scope, presumably file scope.
1305653
1306654=end original
1307655
1308656このことは静的に閉じているレキシカルスコープで宣言されている
1309657C<my> 変数が見えなくなるということは意味しません。
1310658動的変数だけが切り取られます。
1311659例を挙げると、以下の C<bumpx()> はレキシカル変数 $x にアクセスします;
1312660なぜなら、C<my> と C<sub> の両方が同じスコープに現れているからです。
1313661
1314662 my $x = 10;
1315 sub bumpx { $x++ }
663 sub bumpx { $x++ }
1316664
1317665=begin original
1318666
1319667An C<eval()>, however, can see lexical variables of the scope it is
1320668being evaluated in, so long as the names aren't hidden by declarations within
1321669the C<eval()> itself. See L<perlref>.
1322670X<eval, scope of>
1323671
1324672=end original
1325673
1326674しかしながら C<eval()> は、C<eval()> 自身の内側にある宣言によって隠されない
1327675名前の寿命と同じ長さを持つスコープのレキシカル変数を見ることができます。
1328676L<perlref> を参照してください。
1329677X<eval, scope of>
1330678
1331679=begin original
1332680
1333681The parameter list to my() may be assigned to if desired, which allows you
1334682to initialize your variables. (If no initializer is given for a
1335683particular variable, it is created with the undefined value.) Commonly
1336684this is used to name input parameters to a subroutine. Examples:
1337685
1338686=end original
1339687
1340688my() に対するパラーメータリストには、お望みとあらば変数を初期化するための
1341689代入を行うことができます。
1342690(変数に対して初期値が与えられなければ、その変数は未定義値を使って
1343691生成されます。)
1344692一般的にこの機能はサブルーチンに対する入力パラメータに名前を付けるために
1345693使われています。
1346694例:
1347695
1348 $arg = "fred"; # "global" variable
696 $arg = "fred"; # "global" variable
1349697 $n = cube_root(27);
1350698 print "$arg thinks the root is $n\n";
1351 # outputs: fred thinks the root is 3
699 fred thinks the root is 3
1352700
1353701 sub cube_root {
1354 my $arg = shift; # name doesn't matter
702 my $arg = shift; # name doesn't matter
1355 $arg **= 1/3;
703 $arg **= 1/3;
1356 return $arg;
704 return $arg;
1357705 }
1358706
1359707=begin original
1360708
1361709The C<my> is simply a modifier on something you might assign to. So when
1362710you do assign to variables in its argument list, C<my> doesn't
1363711change whether those variables are viewed as a scalar or an array. So
1364712
1365713=end original
1366714
1367715C<my> は、あなたが代入を行いたいと考えている何かに対する修飾子です。
1368716ですから、引数リストの中にある変数に対して代入を行うときには C<my> は
1369717それらの変数がスカラとして見えているのか配列として見えているかという
1370718状態を変えることはありません。ですから、
1371719
1372 my ($foo) = <STDIN>; # WRONG?
720 my ($foo) = <STDIN>; # WRONG?
1373721 my @FOO = <STDIN>;
1374722
1375723=begin original
1376724
1377725both supply a list context to the right-hand side, while
1378726
1379727=end original
1380728
1381729これらの両方ともが右辺をリストコンテキストにするのに対して、
1382730
1383731 my $foo = <STDIN>;
1384732
1385733=begin original
1386734
1387735supplies a scalar context. But the following declares only one variable:
1388736
1389737=end original
1390738
1391739これはスカラコンテキストを与えます。しかし、以下のような宣言を
1392740行った場合、一つの変数だけが有効です:
1393741
1394 my $foo, $bar = 1; # WRONG
742 my $foo, $bar = 1; # WRONG
1395743
1396744=begin original
1397745
1398746That has the same effect as
1399747
1400748=end original
1401749
1402750これは以下のように書いたのと同じことになります
1403751
1404752 my $foo;
1405753 $bar = 1;
1406754
1407755=begin original
1408756
1409757The declared variable is not introduced (is not visible) until after
1410758the current statement. Thus,
1411759
1412760=end original
1413761
1414762宣言された変数は、その文が終了するまでは導入されません(不可視の
1415763状態です)。
1416764したがって、
1417765
1418766 my $x = $x;
1419767
1420768=begin original
1421769
1422770can be used to initialize a new $x with the value of the old $x, and
1423771the expression
1424772
1425773=end original
1426774
1427775これは古い $x の値を使って新しい $x を初期化するのに使うことができます;
1428776そして
1429777
1430778 my $x = 123 and $x == 123
1431779
1432780=begin original
1433781
1434782is false unless the old $x happened to have the value C<123>.
1435783
1436784=end original
1437785
1438786これは古い $x の値がたまたま C<123> でない限り、新しい $x には偽が
1439787設定されます。
1440788
1441789=begin original
1442790
1443791Lexical scopes of control structures are not bounded precisely by the
1444792braces that delimit their controlled blocks; control expressions are
1445793part of that scope, too. Thus in the loop
1446794
1447795=end original
1448796
1449797制御構文のレキシカルスコープは、その制御ブロックを区切る中かっこによって
1450798厳格に束縛されることはありません;
1451799制御式もまた、スコープの一部です。
1452800ですから以下のループでは
1453801
1454802 while (my $line = <>) {
1455803 $line = lc $line;
1456804 } continue {
1457805 print $line;
1458806 }
1459807
1460808=begin original
1461809
1462810the scope of $line extends from its declaration throughout the rest of
1463811the loop construct (including the C<continue> clause), but not beyond
1464812it. Similarly, in the conditional
1465813
1466814=end original
1467815
1468816$line のスコープはその宣言から(C<continue>ブロックを含む)ループ構造の残りの
1469817部分まで拡張されますが、それを越えることはありません。
1470818同様に、以下の条件文では
1471819
1472820 if ((my $answer = <STDIN>) =~ /^yes$/i) {
1473821 user_agrees();
1474822 } elsif ($answer =~ /^no$/i) {
1475823 user_disagrees();
1476824 } else {
1477 chomp $answer;
825 chomp $answer;
1478826 die "'$answer' is neither 'yes' nor 'no'";
1479827 }
1480828
1481829=begin original
1482830
1483831the scope of $answer extends from its declaration through the rest
1484of that conditional, including any C<elsif> and C<else> clauses,
832of that conditional, including any C<elsif> and C<else> clauses,
1485833but not beyond it. See L<perlsyn/"Simple Statements"> for information
1486834on the scope of variables in statements with modifiers.
1487835
1488836=end original
1489837
1490838$answer のスコープはその宣言から条件文の
1491839C<elsif> と C<else> ブロックを含む残りの部分まで拡張されますが、
1492840それを越えることはありません。
1493841修飾子付きの文での変数のスコープに関する情報については
1494842L<perlsyn/"Simple Statements"> を参照してください。
1495843
1496844=begin original
1497845
1498846The C<foreach> loop defaults to scoping its index variable dynamically
1499847in the manner of C<local>. However, if the index variable is
1500848prefixed with the keyword C<my>, or if there is already a lexical
1501849by that name in scope, then a new lexical is created instead. Thus
1502850in the loop
1503851X<foreach> X<for>
1504852
1505853=end original
1506854
1507855C<foreach> はその添え字変数に対するスコープをデフォルトでは
1508856C<local> のやり方で動的なものにしています。
1509857しかしながら、添え字変数に C<my> というキーワードが前置されていた場合、
1510858または現在のスコープでその名前がすでにレキシカルである場合には、
1511859新しいレキシカル変数が代わりに作られます。
1512860ですから以下のループでは:
1513861X<foreach> X<for>
1514862
1515863 for my $i (1, 2, 3) {
1516864 some_function();
1517865 }
1518866
1519867=begin original
1520868
1521869the scope of $i extends to the end of the loop, but not beyond it,
1522870rendering the value of $i inaccessible within C<some_function()>.
1523871X<foreach> X<for>
1524872
1525873=end original
1526874
1527875$i のスコープはループの終端まで拡張されますが、それを越えることはないので、
1528876$i の値は C<some_function()> の中では参照することができなくなります。
1529877X<foreach> X<for>
1530878
1531879=begin original
1532880
1533881Some users may wish to encourage the use of lexically scoped variables.
1534882As an aid to catching implicit uses to package variables,
1535883which are always global, if you say
1536884
1537885=end original
1538886
1539887ユーザーの一部には、レキシカルなスコープの変数の使用を奨励することを
1540888望んでいる人もいるでしょう。
1541889常にグローバルであるパッケージ変数に対する暗黙の使用を捕捉することを
1542890助けるものとして、
1543891
1544892 use strict 'vars';
1545893
1546894=begin original
1547895
1548896then any variable mentioned from there to the end of the enclosing
1549897block must either refer to a lexical variable, be predeclared via
1550898C<our> or C<use vars>, or else must be fully qualified with the package name.
1551899A compilation error results otherwise. An inner block may countermand
1552900this with C<no strict 'vars'>.
1553901
1554902=end original
1555903
1556904のようにすると、この文からそれを囲むブロックの終端までの間の変数の参照は、
1557905レキシカル変数に対する参照か、C<our> または C<use vars> による
1558906事前宣言か、さもなければ完全なパッケージ名で修飾した
1559907名前でなければなりません。
1560908それ以外のものがあるとコンパイルエラーが発生します。
1561909これの対象となっているブロックの内側にあるブロックで
1562910C<no strict 'vars'> とすると(内側のブロック中では)この制限を
1563911取り消すことができます。
1564912
1565913=begin original
1566914
1567915A C<my> has both a compile-time and a run-time effect. At compile
1568916time, the compiler takes notice of it. The principal usefulness
1569917of this is to quiet C<use strict 'vars'>, but it is also essential
1570918for generation of closures as detailed in L<perlref>. Actual
1571919initialization is delayed until run time, though, so it gets executed
1572920at the appropriate time, such as each time through a loop, for
1573921example.
1574922
1575923=end original
1576924
1577925C<my> はコンパイル時の効果と実行時の効果の両方を持っています。
1578926コンパイル時においては、コンパイラはその変数を認識します。
1579927これの基本的な実用性は C<use strict 'vars'> を黙らせるということですが、
1580928L<perlref> で詳細を記述しているクロージャの作成にも有用です。
1581929実際の初期化は実行時まで遅らされ、そのためたとえばループを通る度に
1582930適切に実行されるのです。
1583931
1584932=begin original
1585933
1586934Variables declared with C<my> are not part of any package and are therefore
1587935never fully qualified with the package name. In particular, you're not
1588936allowed to try to make a package variable (or other global) lexical:
1589937
1590938=end original
1591939
1592940C<my> によって宣言された変数はどのパッケージの一部でもなく、
1593941そのためパッケージ名を使って修飾されることは決してありません。
1594942特に、パッケージ変数(もしくはその他のグローバルな変数)を
1595943レキシカルにしようとすることは許されていません。
1596944
1597 my $pack::var; # ERROR! Illegal syntax
945 my $pack::var; # ERROR! Illegal syntax
1598946
1599947=begin original
1600948
1601In fact, a package or global variable is still accessible using the
949In fact, a dynamic variable (also known as package or global variables)
1602950are still accessible using the fully qualified C<::> notation even while a
1603951lexical of the same name is also visible:
1604952
1605953=end original
1606954
1607実際のところ、パッケージまたはグローバル変数は、
955実際のところ、動的変数(パッケージ変数やグローバル変数として
1608同じ名前を持ったレキシカル変数が可視な状態であったとしても、
956知られているもの)は、同じ名前を持ったレキシカルが可視な状態であったとしても、
1609957C<::> 記法を使った(名前の)完全な修飾を行うことによって
1610まだアクセスできます:
958まだアクセス可能なのです:
1611959
1612960 package main;
1613 our $x = 10;
961 local $x = 10;
1614 my $x = 20;
962 my $x = 20;
1615963 print "$x and $::x\n";
1616964
1617965=begin original
1618966
1619967That will print out C<20> and C<10>.
1620968
1621969=end original
1622970
1623971この例は C<20> と C<10> を出力します。
1624972
1625973=begin original
1626974
1627975You may declare C<my> variables at the outermost scope of a file
1628976to hide any such identifiers from the world outside that file. This
1629977is similar in spirit to C's static variables when they are used at
1630978the file level. To do this with a subroutine requires the use of
1631979a closure (an anonymous function that accesses enclosing lexicals).
1632980If you want to create a private subroutine that cannot be called
1633981from outside that block, it can declare a lexical variable containing
1634982an anonymous sub reference:
1635983
1636984=end original
1637985
1638986このファイルの外側の世界からこのような識別子を隠すために、C<my> 変数を
1639987ファイルの最も外側のスコープで宣言することができます。
1640988これは、概念としては C でのファイルレベルの static 変数と似ています。
1641989これをサブルーチンの内側で行うには、
1642990クロージャ(レキシカルアクセスを伴った無名関数)を使います。
1643991ブロックで外側のブロックから呼び出すことのできないようなプライベートな
1644992サブルーチンを作りたいなら、無名サブルーチンのリファレンスを
1645993保持するレキシカル変数を宣言することができます:
1646994
1647995 my $secret_version = '1.001-beta';
1648996 my $secret_sub = sub { print $secret_version };
1649 $secret_sub->();
997 &$secret_sub();
1650998
1651999=begin original
16521000
16531001As long as the reference is never returned by any function within the
16541002module, no outside module can see the subroutine, because its name is not in
16551003any package's symbol table. Remember that it's not I<REALLY> called
16561004C<$some_pack::secret_version> or anything; it's just $secret_version,
16571005unqualified and unqualifiable.
16581006
16591007=end original
16601008
16611009このリファレンスが決して、モジュールの内側にあるどんな関数からも
16621010返されることがないのと同様に、外側のモジュールはサブルーチンを
16631011見ることができません; なぜなら、その名前はどのパッケージのシンボル
16641012テーブルにも存在していないからです。
16651013C<$some_pack::secret_version> などの手段を使って呼び出すことは
16661014B<できない> のだということを思い出してください; これは単なる
16671015$secret_version であって、修飾されることはなく修飾することはできません。
16681016
16691017=begin original
16701018
16711019This does not work with object methods, however; all object methods
16721020have to be in the symbol table of some package to be found. See
16731021L<perlref/"Function Templates"> for something of a work-around to
16741022this.
16751023
16761024=end original
16771025
16781026しかしこれはオブジェクトメソッドと共に動作させることはできません; 全ての
16791027オブジェクトメソッドは、発見可能な何らかのパッケージのシンボルテーブルに
16801028存在している必要があります。
16811029これを回避する方法については L<perlref/"Function Templates"> を
16821030参照してください。
16831031
16841032=head2 Persistent Private Variables
1685X<state> X<state variable> X<static> X<variable, persistent>
1033X<state> X<state variable> X<static> X<variable, persistent> X<variable, static> X<closure>
1686X<variable, static> X<closure>
16871034
16881035(永続的なプライベート変数)
16891036
16901037=begin original
16911038
16921039There are two ways to build persistent private variables in Perl 5.10.
1693First, you can simply use the C<state> feature. Or, you can use closures,
1040First, you can simply use the C<state> feature. Or, you can use closures,
16941041if you want to stay compatible with releases older than 5.10.
16951042
16961043=end original
16971044
16981045Perl 5.10 で永続的プライベート変数を構築するには二つの方法があります。
16991046一つ目は単に C<state> 機能を使うことです。
17001047あるいは、5.10 よりも古いリリースとの互換性を維持したいなら、クロージャを
17011048使うことです。
17021049
17031050=head3 Persistent variables via state()
17041051
17051052(state() による永続変数)
17061053
17071054=begin original
17081055
1709Beginning with Perl 5.10.0, you can declare variables with the C<state>
1056Beginning with Perl 5.9.4, you can declare variables with the C<state>
17101057keyword in place of C<my>. For that to work, though, you must have
17111058enabled that feature beforehand, either by using the C<feature> pragma, or
17121059by using C<-E> on one-liners (see L<feature>). Beginning with Perl 5.16,
17131060the C<CORE::state> form does not require the
17141061C<feature> pragma.
17151062
1063
17161064=end original
17171065
1718perl 5.10.0 から、C<my> の代わりに C<state> キーワードを使って変数を
1066perl 5.9.4 から、C<my> の代わりに C<state> キーワードを使って変数を
17191067宣言できます。
17201068しかし、これを働かせるには、C<feature> プラグマを使うか、一行野郎では
17211069C<-E> を使うことで予めこの機能を有効にしなければなりません
17221070(L<feature> を参照してください)。
17231071Perl 5.16 から、C<CORE::state> 形式は C<feature> プラグマが
17241072不要になりました。
17251073
17261074=begin original
17271075
1728The C<state> keyword creates a lexical variable (following the same scoping
1729rules as C<my>) that persists from one subroutine call to the next. If a
1730state variable resides inside an anonymous subroutine, then each copy of
1731the subroutine has its own copy of the state variable. However, the value
1732of the state variable will still persist between calls to the same copy of
1733the anonymous subroutine. (Don't forget that C<sub { ... }> creates a new
1734subroutine each time it is executed.)
1735
1736=end original
1737
1738The C<state> キーワードは、あるサブルーチン呼び出しから次の呼び出しまで永続する
1739(C<my> と同じスコープ規則に従う)レキシカル変数を作成します。
1740state 変数が無名サブルーチンの中にある場合は、サブルーチンのそれぞれのコピーは
1741独自の state 変数を持ちます。
1742しかし、state 変数の値は同じ無名サブルーチンの呼び出しの間では永続します。
1743(C<sub { ... }> は、実行されるごとに新しいサブルーチンを作ることを
1744忘れないでください。)
1745
1746=begin original
1747
17481076For example, the following code maintains a private counter, incremented
17491077each time the gimme_another() function is called:
17501078
17511079=end original
17521080
17531081例えば、以下のコードはプライベートなカウンタを管理し、gimme_another() 関数が
17541082呼び出されるたびにカウンタを増加させます:
17551083
17561084 use feature 'state';
17571085 sub gimme_another { state $x; return ++$x }
17581086
17591087=begin original
17601088
1761And this example uses anonymous subroutines to create separate counters:
1762
1763=end original
1764
1765そしてこの例は、別々のカウンタを作るために無名サブルーチンを使います:
1766
1767 use feature 'state';
1768 sub create_counter {
1769 return sub { state $x; return ++$x }
1770 }
1771
1772=begin original
1773
17741089Also, since C<$x> is lexical, it can't be reached or modified by any Perl
17751090code outside.
17761091
17771092=end original
17781093
17791094また、C<$x> はレキシカルなので、その外側の Perl コードからアクセスすることは
17801095できません。
17811096
17821097=begin original
17831098
1784When combined with variable declaration, simple assignment to C<state>
1099When combined with variable declaration, simple scalar assignment to C<state>
17851100variables (as in C<state $x = 42>) is executed only the first time. When such
17861101statements are evaluated subsequent times, the assignment is ignored. The
1787behavior of assignment to C<state> declarations where the left hand side
1102behavior of this sort of assignment to non-scalar variables is undefined.
1788of the assignment involves any parentheses is currently undefined.
17891103
17901104=end original
17911105
17921106変数宣言と結び付けられたとき、(C<state $x = 42> のような)C<state> 変数への
1793単純な代入は一度目だけ実行されます。
1107単純なスカラ代入は一度目だけ実行されます。
17941108その後再びこの文が評価されても、代入は無視されます。
1795代入左側にかっが着いている場合C<state> 宣言へ代入の
1109非スカラ変数へのこの種の代入の振る舞いは未定義です。
1796振る舞いは現在のところ未定義です。
17971110
17981111=head3 Persistent variables with closures
17991112
18001113(クロージャによる永続変数)
18011114
18021115=begin original
18031116
18041117Just because a lexical variable is lexically (also called statically)
18051118scoped to its enclosing block, C<eval>, or C<do> FILE, this doesn't mean that
18061119within a function it works like a C static. It normally works more
1807like a C auto, but with implicit garbage collection.
1120like a C auto, but with implicit garbage collection.
18081121
18091122=end original
18101123
18111124レキシカル変数はそれを囲むブロック、C<eval>、C<do> FILE に属する
18121125レキシカル(もしくは静的)スコープに属します; このことは C の static と同様に
18131126動作するということを意味しません。
18141127通常は C の auto と同じように動作しますが、暗黙のガベージコレクションを
18151128伴っています。
18161129
18171130=begin original
18181131
18191132Unlike local variables in C or C++, Perl's lexical variables don't
18201133necessarily get recycled just because their scope has exited.
18211134If something more permanent is still aware of the lexical, it will
18221135stick around. So long as something else references a lexical, that
18231136lexical won't be freed--which is as it should be. You wouldn't want
18241137memory being free until you were done using it, or kept around once you
18251138were done. Automatic garbage collection takes care of this for you.
18261139
18271140=end original
18281141
18291142C や C++ におけるローカル変数とは異なり、Perl のレキシカル変数は
18301143単にそのスコープから抜けたからという理由で、必ずしもリサイクルされません。
18311144何かもっと永続的なものがそのレキシカル変数に関してまだ気付いていれば、
18321145それは留まるでしょう。
18331146何か他のものがレキシカル変数を参照していれば、そのレキシカル変数は
18341147解放されません -- そしてそうあるべきです。
18351148あなたはそれを使いおわるまではメモリを解放したいとは思わないでしょうし、
18361149使い終わったものを保持し続けたいとも思わないでしょう。
18371150あなたのために自動ガベージコレクションがこれを行います。
18381151
18391152=begin original
18401153
18411154This means that you can pass back or save away references to lexical
18421155variables, whereas to return a pointer to a C auto is a grave error.
18431156It also gives us a way to simulate C's function statics. Here's a
18441157mechanism for giving a function private variables with both lexical
18451158scoping and a static lifetime. If you do want to create something like
18461159C's static variables, just enclose the whole function in an extra block,
18471160and put the static variable outside the function but in the block.
18481161
18491162=end original
18501163
18511164これはつまり、レキシカル変数に対するリファレンスを返したり保存したり
18521165することができるということです; 一方 C の auto 変数に対するポインタを
18531166返すことはエラーとなります。
18541167レキシカル変数はまた、C の関数に static な変数のシミュレートも行います。
18551168以下の例はレキシカルスコープを持つと同時に static な寿命を持つ関数に
18561169プライベートな変数です。
18571170C の static 変数のようなものを作りたいというのであれば、
18581171関数全体をさらにブロックで囲んでやり、static 変数をブロックの内側で、
18591172かつ関数の外側の場所においてやります。
18601173
18611174 {
1862 my $secret_val = 0;
1175 my $secret_val = 0;
1863 sub gimme_another {
1176 sub gimme_another {
1864 return ++$secret_val;
1177 return ++$secret_val;
1865 }
1178 }
18661179 }
18671180 # $secret_val now becomes unreachable by the outside
18681181 # world, but retains its value between calls to gimme_another
18691182
18701183=begin original
18711184
18721185If this function is being sourced in from a separate file
18731186via C<require> or C<use>, then this is probably just fine. If it's
18741187all in the main program, you'll need to arrange for the C<my>
18751188to be executed early, either by putting the whole block above
18761189your main program, or more likely, placing merely a C<BEGIN>
18771190code block around it to make sure it gets executed before your program
18781191starts to run:
18791192
18801193=end original
18811194
18821195この関数が C<require> や C<use> を通じて別の独立したファイルから
18831196取り込まれた場合、これはとても役に立つことでしょう。
18841197もしこれがすべてメインプログラムの中にあるのであれば、
18851198ブロック全体をメインプログラムの前に置くか、(こちらか好ましいやり方ですが)
18861199プログラムが実行されるよりも前に実行されることが保証されている
18871200BEGIN コードブロックの中に置くようにして、C<my> を早めに実行するように
18881201変更する必要があるでしょう:
18891202
18901203 BEGIN {
1891 my $secret_val = 0;
1204 my $secret_val = 0;
1892 sub gimme_another {
1205 sub gimme_another {
1893 return ++$secret_val;
1206 return ++$secret_val;
1894 }
1207 }
18951208 }
18961209
18971210=begin original
18981211
18991212See L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END"> about the
19001213special triggered code blocks, C<BEGIN>, C<UNITCHECK>, C<CHECK>,
19011214C<INIT> and C<END>.
19021215
19031216=end original
19041217
19051218特別なトリガーコードブロックである C<BEGIN>, C<CHECK>, C<INIT>, C<END> に
19061219ついては
19071220L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END"> を参照してください。
19081221
19091222=begin original
19101223
19111224If declared at the outermost scope (the file scope), then lexicals
19121225work somewhat like C's file statics. They are available to all
19131226functions in that same file declared below them, but are inaccessible
19141227from outside that file. This strategy is sometimes used in modules
19151228to create private variables that the whole module can see.
19161229
19171230=end original
19181231
19191232最も外側のスコープ(ファイルスコープ)で宣言されたのであれば、
19201233レキシカル変数は C のファイルに static なものと同じように振る舞います。
19211234同じファイルの、宣言の後にある全ての関数から参照可能でありますが、
19221235そのファイルの外側から参照することはできません。
19231236この戦略はモジュールの中でモジュール全体から見える
19241237プライベートな変数を作るために使われます。
19251238
19261239=head2 Temporary Values via local()
19271240X<local> X<scope, dynamic> X<dynamic scope> X<variable, local>
19281241X<variable, temporary>
19291242
19301243(local() を使った一時的な値)
19311244
19321245=begin original
19331246
19341247B<WARNING>: In general, you should be using C<my> instead of C<local>, because
19351248it's faster and safer. Exceptions to this include the global punctuation
19361249variables, global filehandles and formats, and direct manipulation of the
19371250Perl symbol table itself. C<local> is mostly used when the current value
19381251of a variable must be visible to called subroutines.
19391252
19401253=end original
19411254
19421255B<警告>: 一般的には、C<local> ではなくC<my> を使うべきです; なぜなら、そちらの
19431256ほうが早く、安全だからです。
19441257この例外には、グローバルな句読点変数(punctuation variable)、グローバル
19451258ファイルハンドル、フォーマット、そして Perl のシンボルテーブル自身に対する
19461259直接の操作が含まれます。
19471260C<local> はほとんどの場合、変数の現在の値が呼び出されたサブルーチンに
19481261対して可視にしなければならない場合に使われます。
19491262
19501263=begin original
19511264
19521265Synopsis:
19531266
19541267=end original
19551268
19561269概要:
19571270
19581271=begin original
19591272
19601273 # localization of values
19611274
19621275=end original
19631276
19641277 # 値のローカル化
19651278
19661279=begin original
19671280
1968 local $foo; # make $foo dynamically local
1281 local $foo; # make $foo dynamically local
1969 local (@wid, %get); # make list of variables local
1282 local (@wid, %get); # make list of variables local
1970 local $foo = "flurp"; # make $foo dynamic, and init it
1283 local $foo = "flurp"; # make $foo dynamic, and init it
1971 local @oof = @bar; # make @oof dynamic, and init it
1284 local @oof = @bar; # make @oof dynamic, and init it
19721285
19731286=end original
19741287
1975 local $foo; # $foo を動的にローカルにする
1288 local $foo; # $foo を動的にローカルにする
1976 local (@wid, %get); # 変数のリストをローカルにする
1289 local (@wid, %get); # 変数のリストをローカルにする
1977 local $foo = "flurp"; # $foo を動的にして、初期化する
1290 local $foo = "flurp"; # $foo を動的にして、初期化する
1978 local @oof = @bar; # @oof を動的にして、初期化する
1291 local @oof = @bar; # @oof を動的にして、初期化する
19791292
19801293=begin original
19811294
1982 local $hash{key} = "val"; # sets a local value for this hash entry
1295 local $hash{key} = "val"; # sets a local value for this hash entry
1983 delete local $hash{key}; # delete this entry for the current block
1296 delete local $hash{key}; # delete this entry for the current block
1984 local ($cond ? $v1 : $v2); # several types of lvalues support
1297 local ($cond ? $v1 : $v2); # several types of lvalues support
1985 # localization
1298 # localization
19861299
19871300=end original
19881301
1989 local $hash{key} = "val"; # このハッシュエントリにローカルな値を入れる
1302 local $hash{key} = "val"; # このハッシュエントリにローカルな値を入れる
1990 delete local $hash{key}; # 現在のブロックでこのエントリを削除
1303 delete local $hash{key}; # 現在のブロックでこのエントリを削除
1991 local ($cond ? $v1 : $v2); # いくつかの種類の左辺値はローカル化に
1304 local ($cond ? $v1 : $v2); # いくつかの種類の左辺値はローカル化に
1992 # 対応している
1305 # 対応している
19931306
19941307=begin original
19951308
19961309 # localization of symbols
19971310
19981311=end original
19991312
20001313 # シンボルのローカル化
20011314
20021315=begin original
20031316
2004 local *FH; # localize $FH, @FH, %FH, &FH ...
1317 local *FH; # localize $FH, @FH, %FH, &FH ...
2005 local *merlyn = *randal; # now $merlyn is really $randal, plus
1318 local *merlyn = *randal; # now $merlyn is really $randal, plus
2006 # @merlyn is really @randal, etc
1319 # @merlyn is really @randal, etc
2007 local *merlyn = 'randal'; # SAME THING: promote 'randal' to *randal
1320 local *merlyn = 'randal'; # SAME THING: promote 'randal' to *randal
2008 local *merlyn = \$randal; # just alias $merlyn, not @merlyn etc
1321 local *merlyn = \$randal; # just alias $merlyn, not @merlyn etc
20091322
20101323=end original
20111324
2012 local *FH; # $FH, @FH, %FH, &FH ... をローカル化
1325 local *FH; # $FH, @FH, %FH, &FH ... をローカル化
2013 local *merlyn = *randal; # ここで $merlyn は実際には $randal、さらに
1326 local *merlyn = *randal; # ここで $merlyn は実際には $randal、さらに
2014 # @merlyn は実際には @randal、など
1327 # @merlyn は実際には @randal、など
2015 local *merlyn = 'randal'; # 「同様」: 'randal' を *randal にする
1328 local *merlyn = 'randal'; # 「同様」: 'randal' を *randal にする
2016 local *merlyn = \$randal; # 単に $merlyn の別名で @merlyn などではない
1329 local *merlyn = \$randal; # 単に $merlyn の別名で @merlyn などではない
20171330
20181331=begin original
20191332
20201333A C<local> modifies its listed variables to be "local" to the
20211334enclosing block, C<eval>, or C<do FILE>--and to I<any subroutine
20221335called from within that block>. A C<local> just gives temporary
20231336values to global (meaning package) variables. It does I<not> create
20241337a local variable. This is known as dynamic scoping. Lexical scoping
20251338is done with C<my>, which works more like C's auto declarations.
20261339
20271340=end original
20281341
20291342C<local> は、引数に取ったそのリスト中の変数を(local() を囲む)ブロック
20301343(あるいは、サブルーチン, C<eval>、C<do FILE>)と、B<そのブロック中で
20311344呼び出された全てのもの> にローカルなものにします。
20321345C<local> は単にグローバル変数(やパッケージ変数)に一時的な値を与えるだけです。
20331346これはローカル変数を I<作りません>。
20341347これは動的スコープとして知られています。
20351348レキシカルスコープは C<my> を使って行われ、これは C の 自動変数宣言のように
20361349働きます。
20371350
20381351=begin original
20391352
20401353Some types of lvalues can be localized as well: hash and array elements
20411354and slices, conditionals (provided that their result is always
20421355localizable), and symbolic references. As for simple variables, this
20431356creates new, dynamically scoped values.
20441357
20451358=end original
20461359
20471360いくつかの種類の左辺値もローカル化できます: ハッシュと配列の要素とスライス、
20481361条件文(その結果が常にローカル化可能なもの)、シンボリックリファレンス。
20491362単純変数に関しては、これは新しく、動的スコープを持つ値を作ります。
20501363
20511364=begin original
20521365
20531366If more than one variable or expression is given to C<local>, they must be
20541367placed in parentheses. This operator works
20551368by saving the current values of those variables in its argument list on a
20561369hidden stack and restoring them upon exiting the block, subroutine, or
20571370eval. This means that called subroutines can also reference the local
20581371variable, but not the global one. The argument list may be assigned to if
20591372desired, which allows you to initialize your local variables. (If no
20601373initializer is given for a particular variable, it is created with an
20611374undefined value.)
20621375
20631376=end original
20641377
20651378C<local> に対して二つ以上の変数や表現を与えるのならば、それらの変数は括弧で
20661379くくっておかなければなりません。
20671380この演算子は引数リストにある変数のカレントの値を隠れたスタックに保存し、
20681381ブロックやサブルーチン、eval から抜けるときにその値を復帰することによって
20691382動作しています。
20701383これはつまり、呼び出されたサブルーチンからもローカル変数を
20711384参照することができるけれども、グローバルなものを見ることは
20721385できないということです。
20731386引数リストには、好みに応じてリスト中のローカル変数を初期化するための
20741387代入を行うことができます。
20751388(ある特定の変数に対して初期値が与えられなかった場合には、その変数は未定義値を
20761389伴って生成されます。)
20771390
20781391=begin original
20791392
20801393Because C<local> is a run-time operator, it gets executed each time
20811394through a loop. Consequently, it's more efficient to localize your
20821395variables outside the loop.
20831396
20841397=end original
20851398
20861399C<local> は実行時演算子なので、ループで通る度に実行されます。
20871400現在の Perl はメモリの使用に関して改善されていますが、
20881401結果として、ループの外側で変数を宣言したほうがより効率が良いのです。
20891402
20901403=head3 Grammatical note on local()
20911404X<local, context>
20921405
20931406(local() の文法的注意)
20941407
20951408=begin original
20961409
20971410A C<local> is simply a modifier on an lvalue expression. When you assign to
2098a C<local>ized variable, the C<local> doesn't change whether its list is
1411a C<local>ized variable, the C<local> doesn't change whether its list is viewed
2099viewed as a scalar or an array. So
1412as a scalar or an array. So
21001413
21011414=end original
21021415
21031416C<local> は左辺値に対する単なる修飾子です。
21041417局所化された変数に代入を行ったとき、C<local> はそのリストがスカラとして
21051418見えているのか配列として見えているかということを変えることはありません。
21061419ですから、
21071420
21081421 local($foo) = <STDIN>;
21091422 local @FOO = <STDIN>;
21101423
21111424=begin original
21121425
21131426both supply a list context to the right-hand side, while
21141427
21151428=end original
21161429
21171430これらの両方ともが右辺をリストコンテキストにするのに対して、
21181431
21191432 local $foo = <STDIN>;
21201433
21211434=begin original
21221435
21231436supplies a scalar context.
21241437
21251438=end original
21261439
21271440これはスカラコンテキストを与えます.
21281441
21291442=head3 Localization of special variables
21301443X<local, special variable>
21311444
21321445(特殊変数のローカル化)
21331446
21341447=begin original
21351448
21361449If you localize a special variable, you'll be giving a new value to it,
21371450but its magic won't go away. That means that all side-effects related
21381451to this magic still work with the localized value.
21391452
21401453=end original
21411454
21421455特殊変数をローカル化すると、それに新しい値を入れられますが、特殊機能は
21431456なくなりません。
21441457これは、その特殊機能に関係する全ての副作用はローカル化された値に対しても
21451458働くということを意味します。
21461459
21471460=begin original
21481461
21491462This feature allows code like this to work :
21501463
21511464=end original
21521465
21531466この機能は以下のようなコードが動作するようにします:
21541467
21551468 # Read the whole contents of FILE in $slurp
21561469 { local $/ = undef; $slurp = <FILE>; }
21571470
21581471=begin original
21591472
21601473Note, however, that this restricts localization of some values ; for
2161example, the following statement dies, as of Perl 5.10.0, with an error
1474example, the following statement dies, as of perl 5.9.0, with an error
21621475I<Modification of a read-only value attempted>, because the $1 variable is
21631476magical and read-only :
21641477
21651478=end original
21661479
21671480しかし、これはいくつかの値のローカル化を制限することに注意してください;
2168例えば、以下の文は、Perl 5.10.0 からは、
1481例えば、以下の文は、perl 5.9.0 からは、
21691482I<Modification of a read-only value attempted> というエラーで die します;
21701483なぜなら $1 変数はマジカルで読み込み専用だからです:
21711484
21721485 local $1 = 2;
21731486
21741487=begin original
21751488
2176One exception is the default scalar variable: starting with Perl 5.14
1489One exception is the default scalar variable: starting with perl 5.14
21771490C<local($_)> will always strip all magic from $_, to make it possible
21781491to safely reuse $_ in a subroutine.
21791492
21801493=end original
21811494
2182一つの例外は、デフォルトスカラ変数です: Perl 5.14 から、サブルーチン内で
1495一つの例外は、デフォルトスカラ変数です: perl 5.14 から、サブルーチン内で
21831496安全に $_ を再利用できるように、C<local($_)> は常に
21841497全てのマジックを取り除きます。
21851498
21861499=begin original
21871500
21881501B<WARNING>: Localization of tied arrays and hashes does not currently
21891502work as described.
21901503This will be fixed in a future release of Perl; in the meantime, avoid
2191code that relies on any particular behavior of localising tied arrays
1504code that relies on any particular behaviour of localising tied arrays
21921505or hashes (localising individual elements is still okay).
21931506See L<perl58delta/"Localising Tied Arrays and Hashes Is Broken"> for more
21941507details.
21951508X<local, tie>
21961509
21971510=end original
21981511
21991512B<警告>: tie された配列とハッシュのローカル化は現在のところ
22001513記述されたとおりに動作しません。
22011514これは Perl の将来のリリースで修正されます;
22021515当面の間は、tie された配列やハッシュのローカル化によるどのような
22031516振る舞いにも依存しないようなコードにしてください
22041517(個々の要素のローカル化は問題ありません)。
22051518さらなる詳細については
22061519L<perl58delta/"Localising Tied Arrays and Hashes Is Broken"> を
22071520参照してください。
22081521X<local, tie>
22091522
22101523=head3 Localization of globs
22111524X<local, glob> X<glob>
22121525
22131526(グロブのローカル化)
22141527
22151528=begin original
22161529
22171530The construct
22181531
22191532=end original
22201533
22211534以下のような構造は
22221535
22231536 local *name;
22241537
22251538=begin original
22261539
22271540creates a whole new symbol table entry for the glob C<name> in the
22281541current package. That means that all variables in its glob slot ($name,
22291542@name, %name, &name, and the C<name> filehandle) are dynamically reset.
22301543
22311544=end original
22321545
22331546現在のパッケージでグロブ C<name> のための完全に新しいシンボルテーブル
22341547エントリを作成します。
22351548これは、このグロブスロットに入る全ての変数 ($name, @name, %name, &name,
22361549C<name> ファイルハンドル) は動的にリセットされることを意味します。
22371550
22381551=begin original
22391552
22401553This implies, among other things, that any magic eventually carried by
22411554those variables is locally lost. In other words, saying C<local */>
22421555will not have any effect on the internal value of the input record
22431556separator.
22441557
22451558=end original
22461559
22471560これは特に、
22481561最終的にこれらの変数によってもたらされるマジックは局所的には
22491562失われることを意味します。
22501563言い換えると、C<local */> としても、入力レコードセパレータの内部の
22511564値には何の影響も与えないということです。
22521565
22531566=head3 Localization of elements of composite types
2254X<local, composite type element> X<local, array element>
1567X<local, composite type element> X<local, array element> X<local, hash element>
2255X<local, hash element>
22561568
22571569(複合型の要素のローカル化)
22581570
22591571=begin original
22601572
22611573It's also worth taking a moment to explain what happens when you
22621574C<local>ize a member of a composite type (i.e. an array or hash element).
2263In this case, the element is C<local>ized I<by name>. This means that
1575In this case, the element is C<local>ized I<by name>. This means that
22641576when the scope of the C<local()> ends, the saved value will be
22651577restored to the hash element whose key was named in the C<local()>, or
22661578the array element whose index was named in the C<local()>. If that
22671579element was deleted while the C<local()> was in effect (e.g. by a
22681580C<delete()> from a hash or a C<shift()> of an array), it will spring
22691581back into existence, possibly extending an array and filling in the
22701582skipped elements with C<undef>. For instance, if you say
22711583
22721584=end original
22731585
22741586合成型のメンバー(たとえば配列やハッシュの要素)の局所化したときに
22751587どうなるかを説明しましょう。
22761588この場合、その要素は B<名前によって> 局所化が行われます。
22771589これはつまり、C<local> のスコープが終わったときに、C<local> で名前が
22781590使われていたキーを持つハッシュの要素と C<local> で名前が使われていた
22791591配列要素に関して保存されていた値を復帰するということです。
22801592C<local()> が効果を持っているところでそういった要素が削除された場合
22811593(例えばハッシュに対して delete() を使うとか配列に対して
22821594C<shift()>を使う)に、C<local()> の有効範囲を抜けたところで
22831595削除された要素が復活し、配列の拡張と拡張した分の要素の値を
22841596C<undef> にするということを行います。例えば以下のような場合、
22851597
22861598 %hash = ( 'This' => 'is', 'a' => 'test' );
22871599 @ary = ( 0..5 );
22881600 {
2289 local($ary[5]) = 6;
1601 local($ary[5]) = 6;
2290 local($hash{'a'}) = 'drill';
1602 local($hash{'a'}) = 'drill';
2291 while (my $e = pop(@ary)) {
1603 while (my $e = pop(@ary)) {
2292 print "$e . . .\n";
1604 print "$e . . .\n";
2293 last unless $e > 3;
1605 last unless $e > 3;
2294 }
1606 }
2295 if (@ary) {
1607 if (@ary) {
2296 $hash{'only a'} = 'test';
1608 $hash{'only a'} = 'test';
2297 delete $hash{'a'};
1609 delete $hash{'a'};
2298 }
1610 }
22991611 }
23001612 print join(' ', map { "$_ $hash{$_}" } sort keys %hash),".\n";
23011613 print "The array has ",scalar(@ary)," elements: ",
2302 join(', ', map { defined $_ ? $_ : 'undef' } @ary),"\n";
1614 join(', ', map { defined $_ ? $_ : 'undef' } @ary),"\n";
23031615
23041616=begin original
23051617
23061618Perl will print
23071619
23081620=end original
23091621
23101622Perl は以下のような出力をします。
23111623
23121624 6 . . .
23131625 4 . . .
23141626 3 . . .
23151627 This is a test only a test.
23161628 The array has 6 elements: 0, 1, 2, undef, undef, 5
23171629
23181630=begin original
23191631
23201632The behavior of local() on non-existent members of composite
2321types is subject to change in future. The behavior of local()
1633types is subject to change in future.
2322on array elements specified using negative indexes is particularly
2323surprising, and is very likely to change.
23241634
23251635=end original
23261636
23271637複合型の存在していないメンバーに対する local() の振る舞いは
23281638将来変更される予定です。
2329負のインデックスを使って指定された配列要素の local() の振る舞いは
2330特に驚くもので、おそらく変更されます。
23311639
23321640=head3 Localized deletion of elements of composite types
2333X<delete> X<local, composite type element> X<local, array element>
1641X<delete> X<local, composite type element> X<local, array element> X<local, hash element>
2334X<local, hash element>
23351642
2336(複合型の要素のローカル化された削除)
2337
23381643=begin original
23391644
23401645You can use the C<delete local $array[$idx]> and C<delete local $hash{key}>
23411646constructs to delete a composite type entry for the current block and restore
2342it when it ends. They return the array/hash value before the localization,
1647it when it ends. They return the array/hash value before the localization,
23431648which means that they are respectively equivalent to
23441649
23451650=end original
23461651
23471652現在のブロックからある複合型エントリを削除してブロックの終了時に
23481653復元するために、C<delete local $array[$idx]> および
23491654C<delete local $hash{key}> 構文を使えます。
23501655これらはローカル化される前に配列/ハッシュの値を返すので、以下はそれぞれ
23511656等価です:
23521657
23531658 do {
23541659 my $val = $array[$idx];
23551660 local $array[$idx];
23561661 delete $array[$idx];
23571662 $val
23581663 }
23591664
23601665=begin original
23611666
23621667and
23631668
23641669=end original
23651670
23661671および
23671672
23681673 do {
23691674 my $val = $hash{key};
23701675 local $hash{key};
23711676 delete $hash{key};
23721677 $val
23731678 }
23741679
23751680=begin original
23761681
2377except that for those the C<local> is
1682except that for those the C<local> is scoped to the C<do> block. Slices are
2378scoped to the C<do> block. Slices are
23791683also accepted.
23801684
23811685=end original
23821686
23831687但し C<local> は C<do> ブロックのスコープです。
23841688スライスも受け付けられます。
23851689
23861690 my %hash = (
2387 a => [ 7, 8, 9 ],
1691 a => [ 7, 8, 9 ],
2388 b => 1,
1692 b => 1,
23891693 )
23901694
23911695 {
2392 my $x = delete local $hash{a};
1696 my $a = delete local $hash{a};
2393 # $x is [ 7, 8, 9 ]
1697 # $a is [ 7, 8, 9 ]
2394 # %hash is (b => 1)
1698 # %hash is (b => 1)
23951699
2396 {
1700 {
2397 my @nums = delete local @$x[0, 2]
1701 my @nums = delete local @$a[0, 2]
2398 # @nums is (7, 9)
1702 # @nums is (7, 9)
2399 # $x is [ undef, 8 ]
1703 # $a is [ undef, 8 ]
24001704
2401 $x[0] = 999; # will be erased when the scope ends
1705 $a[0] = 999; # will be erased when the scope ends
2402 }
1706 }
2403 # $x is back to [ 7, 8, 9 ]
1707 # $a is back to [ 7, 8, 9 ]
24041708
24051709 }
24061710 # %hash is back to its original state
24071711
1712=head2 Lvalue subroutines
1713X<lvalue> X<subroutine, lvalue>
1714
1715(左辺値サブルーチン)
1716
24081717=begin original
24091718
2410This construct is supported since Perl v5.12.
1719B<WARNING>: Lvalue subroutines are still experimental and the
1720implementation may change in future versions of Perl.
24111721
24121722=end original
24131723
2414この構文は Perl v5.12 から対応しています。
1724B<警告>: 左辺値サブルーチンは未だ実験的機能であり、
1725将来のバージョンの Perl では実装が変更されるかもしれません。
24151726
2416=head2 Lvalue subroutines
2417X<lvalue> X<subroutine, lvalue>
2418
2419(左辺値サブルーチン)
2420
24211727=begin original
24221728
24231729It is possible to return a modifiable value from a subroutine.
24241730To do this, you have to declare the subroutine to return an lvalue.
24251731
24261732=end original
24271733
24281734サブルーチンから、変更可能な値を返すことが可能です。
24291735そうするためには、サブルーチンが左辺値を返すように宣言しなければなりません。
24301736
24311737 my $val;
24321738 sub canmod : lvalue {
2433 $val; # or: return $val;
1739 $val; # or: return $val;
24341740 }
24351741 sub nomod {
2436 $val;
1742 $val;
24371743 }
24381744
24391745 canmod() = 5; # assigns to $val
24401746 nomod() = 5; # ERROR
24411747
24421748=begin original
24431749
24441750The scalar/list context for the subroutine and for the right-hand
24451751side of assignment is determined as if the subroutine call is replaced
2446by a scalar. For example, consider:
1752by a scalar. For example, consider:
24471753
24481754=end original
24491755
24501756サブルーチンと、代入の右側のスカラ/リストコンテキストは
24511757サブルーチン呼び出しがスカラに置き換えられたかのようにして
24521758決定されます。
24531759例として、以下を考えると:
24541760
24551761 data(2,3) = get_data(3,4);
24561762
24571763=begin original
24581764
24591765Both subroutines here are called in a scalar context, while in:
24601766
24611767=end original
24621768
24631769両方のサブルーチンはスカラコンテキストで呼び出され、一方:
24641770
24651771 (data(2,3)) = get_data(3,4);
24661772
24671773=begin original
24681774
24691775and in:
24701776
24711777=end original
24721778
24731779及び:
24741780
24751781 (data(2),data(3)) = get_data(3,4);
24761782
24771783=begin original
24781784
24791785all the subroutines are called in a list context.
24801786
24811787=end original
24821788
24831789については全てのサブルーチンはリストコンテキストで呼び出されます。
24841790
2485=begin original
1791=over 4
24861792
2487Lvalue subroutines are convenient, but you have to keep in mind that,
1793=item Lvalue subroutines are EXPERIMENTAL
2488when used with objects, they may violate encapsulation. A normal
2489mutator can check the supplied argument before setting the attribute
2490it is protecting, an lvalue subroutine cannot. If you require any
2491special processing when storing and retrieving the values, consider
2492using the CPAN module Sentinel or something similar.
24931794
2494=end original
2495
2496左辺値サブルーチンは便利ですが、オブジェクトに対して使うと、カプセル化に
2497違反するかも知れないことを心に留めておく必要があります。
2498通常のミューテータは、指定された引数を守られている属性に代入する前に
2499チェックできますが、左辺値サブルーチンはできません。
2500値の補完と取り出しに何らかの特別処理が必要な場合は、CPAN モジュールの
2501Sentinel または似たようなものを使うことを考慮してください。
2502
2503=head2 Lexical Subroutines
2504X<my sub> X<state sub> X<our sub> X<subroutine, lexical>
2505
2506(レキシカルサブルーチン)
2507
25081795=begin original
25091796
2510Beginning with Perl 5.18, you can declare a private subroutine with C<my>
1797They appear to be convenient, but there is at least one reason to be
2511or C<state>. As with state variables, the C<state> keyword is only
1798circumspect.
2512available under C<use feature 'state'> or C<use v5.10> or higher.
25131799
25141800=end original
25151801
2516Perl 5.18 からC<my> や C<state> を使ってプライベートサブルーチンを
1802これは便利なようですが慎重にるべき少なくとも一つの理由があります。
2517宣言できます。
2518state 変数の場合、C<state> キーワードは C<use feature 'state'> または
2519C<use v5.10> またはそれ以上の下でのみ利用可能です。
25201803
25211804=begin original
25221805
2523Prior to Perl 5.26, lexical subroutines were deemed experimental and were
1806They violate encapsulation. A normal mutator can check the supplied
2524available only under the C<use feature 'lexical_subs'> pragma. They also
1807argument before setting the attribute it is protecting, an lvalue
2525produced a warning unless the "experimental::lexical_subs" warnings
1808subroutine never gets that chance. Consider;
2526category was disabled.
25271809
25281810=end original
25291811
2530Perl 5.26 より前で、レキシカルサブルーチンは実験的と見なされ、
1812これはカプセ化に違反しています。
2531C<use feature 'lexical_subs'> プラグマの下でのみ利用可能でた。
1813通常の mutator は、自身が保護ている属性にセットする前に
2532"experimental::lexical_subs" 警告カテゴリを無効にしない限り
1814引数をチェックできすが
2533警告が発生していした
1815左辺値サブルーチンにはその機会はありせん
1816以下を考えてみてください;
25341817
2535=begin original
1818 my $some_array_ref = []; # protected by mutators ??
25361819
2537These subroutines are only visible within the block in which they are
1820 sub set_arr { # normal mutator
2538declared, and only after that declaration:
1821 my $val = shift;
1822 die("expected array, you supplied ", ref $val)
2540=end original
1823 unless ref $val eq 'ARRAY';
1824 $some_array_ref = $val;
2542これらのサブルーチンは、宣言されたブロックの内側で、宣言された後でのみ
2543見えます:
2544
2545 # Include these two lines if your code is intended to run under Perl
2546 # versions earlier than 5.26.
2547 no warnings "experimental::lexical_subs";
2548 use feature 'lexical_subs';
2549
2550 foo(); # calls the package/global subroutine
2551 state sub foo {
2552 foo(); # also calls the package subroutine
25531825 }
2554 foo(); # calls "state" sub
1826 sub set_arr_lv : lvalue { # lvalue mutator
2555 my $ref = \&foo; # take a reference to "state" sub
1827 $some_array_ref;
2556
2557 my sub bar { ... }
2558 bar(); # calls "my" sub
2559
2560=begin original
2561
2562You can't (directly) write a recursive lexical subroutine:
2563
2564=end original
2565
2566(直接)再帰レキシカルサブルーチンを書くことは出来ません:
2567
2568 # WRONG
2569 my sub baz {
2570 baz();
25711828 }
25721829
2573=begin original
1830 # set_arr_lv cannot stop this !
1831 set_arr_lv() = { a => 1 };
25741832
2575This example fails because C<baz()> refers to the package/global subroutine
1833=back
2576C<baz>, not the lexical subroutine currently being defined.
25771834
2578=end original
2579
2580This example fails because
2581C<baz()> は、現在定義しているレキシカルサブルーチンではなく、
2582パッケージ/グローバルサブルーチン C<baz> を参照するので、
2583この例は失敗します。
2584
2585=begin original
2586
2587The solution is to use L<C<__SUB__>|perlfunc/__SUB__>:
2588
2589=end original
2590
2591解決法は、L<C<__SUB__>|perlfunc/__SUB__> を使うことです:
2592
2593 my sub baz {
2594 __SUB__->(); # calls itself
2595 }
2596
2597=begin original
2598
2599It is possible to predeclare a lexical subroutine. The C<sub foo {...}>
2600subroutine definition syntax respects any previous C<my sub;> or C<state sub;>
2601declaration. Using this to define recursive subroutines is a bad idea,
2602however:
2603
2604=end original
2605
2606レキシカルサブルーチンを先行宣言することは可能です。
2607C<sub foo {...}> サブルーチン宣言文法は、先行する C<my sub;> または
2608C<state sub;> 宣言を考慮します。
2609しかし、これを再帰サブルーチンを定義するのに使うのは良くない考えです:
2610
2611 my sub baz; # predeclaration
2612 sub baz { # define the "my" sub
2613 baz(); # WRONG: calls itself, but leaks memory
2614 }
2615
2616=begin original
2617
2618Just like C<< my $f; $f = sub { $f->() } >>, this example leaks memory. The
2619name C<baz> is a reference to the subroutine, and the subroutine uses the name
2620C<baz>; they keep each other alive (see L<perlref/Circular References>).
2621
2622=end original
2623
2624C<< my $f; $f = sub { $f->() } >> と同様、この例はメモリリークします。
2625C<baz> という名前はサブルーチンへのリファレンスで、
2626サブルーチンは C<baz> という名前を使います;
2627これは互いに相手を有効にします (L<perlref/Circular References> 参照)。
2628
2629=head3 C<state sub> vs C<my sub>
2630
2631=begin original
2632
2633What is the difference between "state" subs and "my" subs? Each time that
2634execution enters a block when "my" subs are declared, a new copy of each
2635sub is created. "State" subroutines persist from one execution of the
2636containing block to the next.
2637
2638=end original
2639
2640"state" サブルーチンと "my" サブルーチンの違いはなんでしょう?
2641"my" サブルーチンが宣言されていると、ブロックが実行される毎に新しい
2642サブルーチンが作成されます。
2643"state" サブルーチンは、一度目の内部のブロックの実行から次まで永続します。
2644
2645=begin original
2646
2647So, in general, "state" subroutines are faster. But "my" subs are
2648necessary if you want to create closures:
2649
2650=end original
2651
2652したがって、一般的に、"state" サブルーチンの方が速いです。
2653しかし、クロージャを作成したいときには "my" サブルーチンが必要です:
2654
2655 sub whatever {
2656 my $x = shift;
2657 my sub inner {
2658 ... do something with $x ...
2659 }
2660 inner();
2661 }
2662
2663=begin original
2664
2665In this example, a new C<$x> is created when C<whatever> is called, and
2666also a new C<inner>, which can see the new C<$x>. A "state" sub will only
2667see the C<$x> from the first call to C<whatever>.
2668
2669=end original
2670
2671この例で、C<whatever> が呼び出されたときに新しい C<$x> が作成され、さらに
2672新しい C<$x> が見える新しい C<inner> が作成されます。
2673"state" サブルーチンは最初の C<whatever> の呼び出しからの C<$x> だけが
2674見えます。
2675
2676=head3 C<our> subroutines
2677
2678(C<our> サブルーチン)
2679
2680=begin original
2681
2682Like C<our $variable>, C<our sub> creates a lexical alias to the package
2683subroutine of the same name.
2684
2685=end original
2686
2687C<our $variable> と同様、C<our sub> は同じ名前のパッケージサブルーチンへの
2688レキシカルな別名を作成します。
2689
2690=begin original
2691
2692The two main uses for this are to switch back to using the package sub
2693inside an inner scope:
2694
2695=end original
2696
2697これの主な二つの使用法は、内側のスコープの内側のパッケージサブルーチンを
2698使うために切り替えのためです:
2699
2700 sub foo { ... }
2701
2702 sub bar {
2703 my sub foo { ... }
2704 {
2705 # need to use the outer foo here
2706 our sub foo;
2707 foo();
2708 }
2709 }
2710
2711=begin original
2712
2713and to make a subroutine visible to other packages in the same scope:
2714
2715=end original
2716
2717もう一つは同じスコープのほかのパッケージから見えるサブルーチンを作ることです:
2718
2719 package MySneakyModule;
2720
2721 our sub do_something { ... }
2722
2723 sub do_something_with_caller {
2724 package DB;
2725 () = caller 1; # sets @DB::args
2726 do_something(@args); # uses MySneakyModule::do_something
2727 }
2728
27291835=head2 Passing Symbol Table Entries (typeglobs)
27301836X<typeglob> X<*>
27311837
27321838(シンボルテーブルのエントリを渡す(型グロブ))
27331839
27341840=begin original
27351841
27361842B<WARNING>: The mechanism described in this section was originally
27371843the only way to simulate pass-by-reference in older versions of
27381844Perl. While it still works fine in modern versions, the new reference
27391845mechanism is generally easier to work with. See below.
27401846
27411847=end original
27421848
27431849B<警告>: このセクションで説明されている仕組みは、古いバージョンの Perl に
27441850おいて参照渡しをシミュレートするための唯一の方法でした。
27451851これは現在でも使うことができるのですが、新しいリファレンスの仕組みは
27461852これをより簡単に行います。後の説明を参照してください。
27471853
27481854=begin original
27491855
27501856Sometimes you don't want to pass the value of an array to a subroutine
27511857but rather the name of it, so that the subroutine can modify the global
2752copy of it rather than working with a local copy. In Perl you can
1858copy of it rather than working with a local copy. In perl you can
27531859refer to all objects of a particular name by prefixing the name
27541860with a star: C<*foo>. This is often known as a "typeglob", because the
27551861star on the front can be thought of as a wildcard match for all the
27561862funny prefix characters on variables and subroutines and such.
27571863
27581864=end original
27591865
27601866サブルーチンが渡された配列のローカルなコピーではなくてグローバルな
27611867ものの変更ができるように、サブルーチンに対して配列の値ではなく
27621868配列の名前を渡したくなることもあるでしょう。
2763Perl においては、これを C<*foo> のようにアスタリスクを使って
1869perl においては、これを C<*foo> のようにアスタリスクを使って
27641870行うことができます。
27651871これは前に置かれたアスタリスクが変数やサブルーチンなどに対して使われる
2766前置文字全てにマッチするワイルドカードとしてみなすことが
1872前置キャラクター全てにマッチするワイルドカードとしてみなすことが
27671873できるので、“型グロブ”としてよく知られています。
27681874
27691875=begin original
27701876
27711877When evaluated, the typeglob produces a scalar value that represents
27721878all the objects of that name, including any filehandle, format, or
27731879subroutine. When assigned to, it causes the name mentioned to refer to
27741880whatever C<*> value was assigned to it. Example:
27751881
27761882=end original
27771883
27781884型グロブは評価されたときにその名前を持つ全てのオブジェクト(ファイルハンドル、
27791885フォーマット、サブルーチンも含まれます)を表すスカラ値を生成します。
27801886代入が行われたとき、C<*> は代入したものを反映するようになります。
27811887例:
27821888
27831889 sub doubleary {
2784 local(*someary) = @_;
1890 local(*someary) = @_;
2785 foreach $elem (@someary) {
1891 foreach $elem (@someary) {
2786 $elem *= 2;
1892 $elem *= 2;
2787 }
1893 }
27881894 }
27891895 doubleary(*foo);
27901896 doubleary(*bar);
27911897
27921898=begin original
27931899
27941900Scalars are already passed by reference, so you can modify
27951901scalar arguments without using this mechanism by referring explicitly
27961902to C<$_[0]> etc. You can modify all the elements of an array by passing
27971903all the elements as scalars, but you have to use the C<*> mechanism (or
27981904the equivalent reference mechanism) to C<push>, C<pop>, or change the size of
27991905an array. It will certainly be faster to pass the typeglob (or reference).
28001906
28011907=end original
28021908
28031909スカラは既に参照渡しされているので、陽に C<$_[0]> などで参照して
28041910この機構を使わなくてもスカラ引数を変更することができます。
28051911全ての要素がスカラとして渡された配列の要素はすべて
28061912変更することができますが、C<push>、C<pop>、もしくは配列のサイズを
28071913変更するためには C<*> 機構(もしくは同等のリファレンス機構)を
28081914使う必要があります。
28091915これは型グロブ(もしくはリファレンス)を渡すのを確実に高速にするでしょう。
28101916
28111917=begin original
28121918
28131919Even if you don't want to modify an array, this mechanism is useful for
28141920passing multiple arrays in a single LIST, because normally the LIST
28151921mechanism will merge all the array values so that you can't extract out
28161922the individual arrays. For more on typeglobs, see
28171923L<perldata/"Typeglobs and Filehandles">.
28181924
28191925=end original
28201926
28211927配列の変更を望まないとしても、この機構は単一のリストの中にある複数の
28221928リストを渡すのに便利です; なぜなら、通常はリスト機構はすべての配列の値を
28231929結合してしまうので独立した配列を取り出すことができないからです。
28241930型グロブについては、
28251931L<perldata/"Typeglobs and Filehandles"> も参照してください。
28261932
28271933=head2 When to Still Use local()
28281934X<local> X<variable, local>
28291935
28301936(今でも local() を使うとき)
28311937
28321938=begin original
28331939
28341940Despite the existence of C<my>, there are still three places where the
28351941C<local> operator still shines. In fact, in these three places, you
28361942I<must> use C<local> instead of C<my>.
28371943
28381944=end original
28391945
28401946C<my> があるにも関らず、今でも C<local> 演算子を使うべき場所が三ヶ所あります。
28411947実際にはその三ヶ所においては、C<my> ではなく、B<必ず> C<local> を
28421948使わなければなりません。
28431949
28441950=over 4
28451951
28461952=item 1.
28471953
28481954=begin original
28491955
28501956You need to give a global variable a temporary value, especially $_.
28511957
28521958=end original
28531959
28541960グローバル変数(特に C<$_>) に関して、一時的な値を与えたいとき。
28551961
28561962=begin original
28571963
2858The global variables, like C<@ARGV> or the punctuation variables, must be
1964The global variables, like C<@ARGV> or the punctuation variables, must be
28591965C<local>ized with C<local()>. This block reads in F</etc/motd>, and splits
28601966it up into chunks separated by lines of equal signs, which are placed
28611967in C<@Fields>.
28621968
28631969=end original
28641970
28651971C<@ARGV> や句読点変数(punctuation variables)のようなグローバル変数では、
28661972局所化のために C<local()> を使わなければなりません。
28671973以下のブロックは F</etc/motd> を読み込み、等価記号を使って行の塊を分割し、
28681974その結果を C<@Fields> に格納します。
28691975
28701976 {
2871 local @ARGV = ("/etc/motd");
1977 local @ARGV = ("/etc/motd");
28721978 local $/ = undef;
2873 local $_ = <>;
1979 local $_ = <>;
2874 @Fields = split /^\s*=+\s*$/;
1980 @Fields = split /^\s*=+\s*$/;
2875 }
1981 }
28761982
28771983=begin original
28781984
2879In particular, it's important to C<local>ize $_ in any routine that assigns
1985It particular, it's important to C<local>ize $_ in any routine that assigns
28801986to it. Look out for implicit assignments in C<while> conditionals.
28811987
28821988=end original
28831989
28841990特に重要なのは、任意のルーチンの中で $_ を局所化し、それに対して
28851991代入することです。
28861992C<while> 文での暗黙的な代入に注意してください。
28871993
28881994=item 2.
28891995
28901996=begin original
28911997
28921998You need to create a local file or directory handle or a local function.
28931999
28942000=end original
28952001
28962002ローカルなファイルハンドルやディレクトリハンドル、
28972003もしくはローカル関数を作成する必要がある場合。
28982004
28992005=begin original
29002006
29012007A function that needs a filehandle of its own must use
29022008C<local()> on a complete typeglob. This can be used to create new symbol
29032009table entries:
29042010
29052011=end original
29062012
29072013関数に固有のファイルハンドルが必要な関数は、完全な型グロブを使った
29082014C<local()> を使わなければなりません。
29092015これによって、新しいシンボルテーブルのエントリが作成されます:
29102016
29112017 sub ioqueue {
29122018 local (*READER, *WRITER); # not my!
29132019 pipe (READER, WRITER) or die "pipe: $!";
29142020 return (*READER, *WRITER);
29152021 }
29162022 ($head, $tail) = ioqueue();
29172023
29182024=begin original
29192025
29202026See the Symbol module for a way to create anonymous symbol table
29212027entries.
29222028
29232029=end original
29242030
29252031無名シンボルテーブルを生成する方法については、Symbol モジュールを
29262032参照してください。
29272033
29282034=begin original
29292035
29302036Because assignment of a reference to a typeglob creates an alias, this
29312037can be used to create what is effectively a local function, or at least,
29322038a local alias.
29332039
29342040=end original
29352041
29362042型グロブに対するリファレンスの代入はエイリアスを生成するので、
29372043以下の例では効果的にローカル関数(あるいは少なくともローカルエイリアス)を
29382044生成するのに使うことができます。
29392045
29402046 {
29412047 local *grow = \&shrink; # only until this block exits
2942 grow(); # really calls shrink()
2048 grow(); # really calls shrink()
2943 move(); # if move() grow()s, it shrink()s too
2049 move(); # if move() grow()s, it shrink()s too
29442050 }
2945 grow(); # get the real grow() again
2051 grow(); # get the real grow() again
29462052
29472053=begin original
29482054
29492055See L<perlref/"Function Templates"> for more about manipulating
29502056functions by name in this way.
29512057
29522058=end original
29532059
29542060こういったやり方で、名前によって関数を操作する方法に関しての詳細は
29552061L<perlref/"Function Templates"> を参照してください。
29562062
29572063=item 3.
29582064
29592065=begin original
29602066
29612067You want to temporarily change just one element of an array or hash.
29622068
29632069=end original
29642070
29652071配列やハッシュのある要素だけを一時的に変更したい場合。
29662072
29672073=begin original
29682074
29692075You can C<local>ize just one element of an aggregate. Usually this
29702076is done on dynamics:
29712077
29722078=end original
29732079
29742080一つの要素だけを局所化することが可能です。
29752081通常はこれは動的に行われます。
29762082
29772083 {
2978 local $SIG{INT} = 'IGNORE';
2084 local $SIG{INT} = 'IGNORE';
2979 funct(); # uninterruptible
2085 funct(); # uninterruptible
2980 }
2086 }
29812087 # interruptibility automatically restored here
29822088
29832089=begin original
29842090
2985But it also works on lexically declared aggregates.
2091But it also works on lexically declared aggregates. Prior to 5.005,
2092this operation could on occasion misbehave.
29862093
29872094=end original
29882095
29892096しかし、これはレキシカル変数であっても動作します。
20975.005 より前のものでは、この操作は間違った状況になる可能性がありました。
29902098
29912099=back
29922100
29932101=head2 Pass by Reference
29942102X<pass by reference> X<pass-by-reference> X<reference>
29952103
29962104(参照渡し)
29972105
29982106=begin original
29992107
30002108If you want to pass more than one array or hash into a function--or
30012109return them from it--and have them maintain their integrity, then
30022110you're going to have to use an explicit pass-by-reference. Before you
30032111do that, you need to understand references as detailed in L<perlref>.
30042112This section may not make much sense to you otherwise.
30052113
30062114=end original
30072115
30082116もし、配列やハッシュを二つ以上関数に渡したいとか関数から返したいと
30092117考えていて、同時にそれらを完全な状態で扱いたいというのであれば、
30102118明示的に参照渡しを使う必要があるでしょう。
30112119これを行う前に、L<perlref> で説明されているリファレンスを理解する
30122120必要があります。
30132121このセクションでは改めて説明するようなことはしません。
30142122
30152123=begin original
30162124
30172125Here are a few simple examples. First, let's pass in several arrays
3018to a function and have it C<pop> all of them, returning a new list
2126to a function and have it C<pop> all of then, returning a new list
30192127of all their former last elements:
30202128
30212129=end original
30222130
30232131幾つか単純な例を挙げましょう。
30242132まず最初に、ある関数に幾つかの配列を渡し、
30252133全ての配列に対して C<pop> を行って引数として受け取った配列の
30262134それぞれの最後の要素からなる新しいリストを返すということを
30272135考えてみましょう。
30282136
3029 @tailings = popmany ( \@w, \@x, \@y, \@z );
2137 @tailings = popmany ( \@a, \@b, \@c, \@d );
30302138
30312139 sub popmany {
3032 my $aref;
2140 my $aref;
3033 my @retlist;
2141 my @retlist = ();
3034 foreach $aref ( @_ ) {
2142 foreach $aref ( @_ ) {
3035 push @retlist, pop @$aref;
2143 push @retlist, pop @$aref;
3036 }
2144 }
3037 return @retlist;
2145 return @retlist;
30382146 }
30392147
30402148=begin original
30412149
30422150Here's how you might write a function that returns a
30432151list of keys occurring in all the hashes passed to it:
30442152
30452153=end original
30462154
30472155以下の例は、引数として渡された全てのハッシュにあるキーのリストを
30482156返す関数です:
30492157
30502158 @common = inter( \%foo, \%bar, \%joe );
30512159 sub inter {
3052 my ($k, $href, %seen); # locals
2160 my ($k, $href, %seen); # locals
3053 foreach $href (@_) {
2161 foreach $href (@_) {
3054 while ( $k = each %$href ) {
2162 while ( $k = each %$href ) {
3055 $seen{$k}++;
2163 $seen{$k}++;
3056 }
2164 }
3057 }
2165 }
3058 return grep { $seen{$_} == @_ } keys %seen;
2166 return grep { $seen{$_} == @_ } keys %seen;
30592167 }
30602168
30612169=begin original
30622170
30632171So far, we're using just the normal list return mechanism.
30642172What happens if you want to pass or return a hash? Well,
30652173if you're using only one of them, or you don't mind them
30662174concatenating, then the normal calling convention is ok, although
30672175a little expensive.
30682176
30692177=end original
30702178
30712179とはいうものの、これは通常のリストを返す機構を使っています。
30722180ハッシュを渡そうとしたり、ハッシュを返そうとすると何が起きるのでしょうか?
30732181そうです、引数の一つだけを使い引数の連結が行われることを気にしなければ
30742182通常の呼び出し規約と同じことです; ただし、少々高くつきます。
30752183
30762184=begin original
30772185
30782186Where people get into trouble is here:
30792187
30802188=end original
30812189
30822190このように書くのはトラブルのもとです:
30832191
3084 (@w, @x) = func(@y, @z);
2192 (@a, @b) = func(@c, @d);
30852193or
3086 (%w, %x) = func(%y, %z);
2194 (%a, %b) = func(%c, %d);
30872195
30882196=begin original
30892197
3090That syntax simply won't work. It sets just C<@w> or C<%w> and
2198That syntax simply won't work. It sets just C<@a> or C<%a> and
3091clears the C<@x> or C<%x>. Plus the function didn't get passed
2199clears the C<@b> or C<%b>. Plus the function didn't get passed
30922200into two separate arrays or hashes: it got one long list in C<@_>,
30932201as always.
30942202
30952203=end original
30962204
30972205これらの構文は単純にうまくいきません。
3098戻り値は C<@w>や C<%w> だけにセットされて、C<@x> や C<%x> はクリアされます。
2206戻り値は C<@a>や C<%a>だけにセットされて、C<@b> や C<%b> はクリアされます。
30992207それに加え、この関数は引数として二つの配列、二つのハッシュを受け取りません:
31002208受け取るのは常に C<@_> に格納されている(二つの引数の内容が連結された)一つの
31012209長いリストなのです。
31022210
31032211=begin original
31042212
31052213If you can arrange for everyone to deal with this through references, it's
31062214cleaner code, although not so nice to look at. Here's a function that
31072215takes two array references as arguments, returning the two array elements
31082216in order of how many elements they have in them:
31092217
31102218=end original
31112219
31122220これをリファレンス経由で扱うように変更できるのであれば、見た目はそれ程
31132221良くありませんがプログラムを明確にできます。
31142222以下の例は引数として配列のリファレンスを二つ取り、その配列の要素の数によって
31152223順序づけられた二つの配列を返す関数です:
31162224
3117 ($wref, $xref) = func(\@y, \@z);
2225 ($aref, $bref) = func(\@c, \@d);
3118 print "@$wref has more than @$xref\n";
2226 print "@$aref has more than @$bref\n";
31192227 sub func {
3120 my ($yref, $zref) = @_;
2228 my ($cref, $dref) = @_;
3121 if (@$yref > @$zref) {
2229 if (@$cref > @$dref) {
3122 return ($yref, $zref);
2230 return ($cref, $dref);
3123 } else {
2231 } else {
3124 return ($zref, $yref);
2232 return ($dref, $cref);
3125 }
2233 }
31262234 }
31272235
31282236=begin original
31292237
31302238It turns out that you can actually do this also:
31312239
31322240=end original
31332241
31342242これは以下のように書くこともできます:
31352243
3136 (*w, *x) = func(\@y, \@z);
2244 (*a, *b) = func(\@c, \@d);
3137 print "@w has more than @x\n";
2245 print "@a has more than @b\n";
31382246 sub func {
3139 local (*y, *z) = @_;
2247 local (*c, *d) = @_;
3140 if (@y > @z) {
2248 if (@c > @d) {
3141 return (\@y, \@z);
2249 return (\@c, \@d);
3142 } else {
2250 } else {
3143 return (\@z, \@y);
2251 return (\@d, \@c);
3144 }
2252 }
31452253 }
31462254
31472255=begin original
31482256
31492257Here we're using the typeglobs to do symbol table aliasing. It's
31502258a tad subtle, though, and also won't work if you're using C<my>
31512259variables, because only globals (even in disguise as C<local>s)
31522260are in the symbol table.
31532261
31542262=end original
31552263
31562264この例では、シンボルテーブルの別名づけをするために型グロブを使っています。
31572265しかし、これは微妙なものであり、C<my> 変数を使った場合にはうまくいきません;
31582266なぜなら、グローバルなもの(C<local()> で偽装したものを含む)だけが
31592267シンボルテーブルにあるからです。
31602268
31612269=begin original
31622270
31632271If you're passing around filehandles, you could usually just use the bare
31642272typeglob, like C<*STDOUT>, but typeglobs references work, too.
31652273For example:
31662274
31672275=end original
31682276
31692277ファイルハンドルを扱おうというのであれば、通常は C<*STDOUT> のような
31702278裸の型グロブ(bare typeglob)を使うことができますが、型グロブの
31712279リファレンスも動作します。
31722280例えば:
31732281
31742282 splutter(\*STDOUT);
31752283 sub splutter {
3176 my $fh = shift;
2284 my $fh = shift;
3177 print $fh "her um well a hmmm\n";
2285 print $fh "her um well a hmmm\n";
31782286 }
31792287
31802288 $rec = get_rec(\*STDIN);
31812289 sub get_rec {
3182 my $fh = shift;
2290 my $fh = shift;
3183 return scalar <$fh>;
2291 return scalar <$fh>;
31842292 }
31852293
31862294=begin original
31872295
31882296If you're planning on generating new filehandles, you could do this.
31892297Notice to pass back just the bare *FH, not its reference.
31902298
31912299=end original
31922300
31932301新しいファイルハンドルを生成することを考えているのであれば、
31942302以下のようにできます。
31952303リファレンスではなく、生の *FH を渡すことに注意してください。
31962304
31972305 sub openit {
3198 my $path = shift;
2306 my $path = shift;
3199 local *FH;
2307 local *FH;
3200 return open (FH, $path) ? *FH : undef;
2308 return open (FH, $path) ? *FH : undef;
32012309 }
32022310
32032311=head2 Prototypes
32042312X<prototype> X<subroutine, prototype>
32052313
32062314(プロトタイプ)
32072315
32082316=begin original
32092317
32102318Perl supports a very limited kind of compile-time argument checking
3211using function prototyping. This can be declared in either the PROTO
2319using function prototyping. If you declare
3212section or with a L<prototype attribute|attributes/Built-in Attributes>.
3213If you declare either of
32142320
32152321=end original
32162322
32172323Perl はとても限られた形のコンパイル時引数チェックに対応しています。
3218これは PROTO セクションか
2324以下のように宣言すると:
3219L<プロトタイプ属性|attributes/Built-in Attributes> で宣言できます。
3220以下のどちらかのように宣言すると:
32212325
3222 sub mypush (\@@)
2326 sub mypush (+@)
3223 sub mypush :prototype(\@@)
32242327
32252328=begin original
32262329
3227then C<mypush()> takes arguments exactly like C<push()> does.
2330then C<mypush()> takes arguments exactly like C<push()> does. The
3228
3229=end original
3230
3231C<mypush()> は C<push()> が取るのとまったく同じ引数を取ります。
3232
3233=begin original
3234
3235If subroutine signatures are enabled (see L</Signatures>), then
3236the shorter PROTO syntax is unavailable, because it would clash with
3237signatures. In that case, a prototype can only be declared in the form
3238of an attribute.
3239
3240=end original
3241
3242サブルーチンシグネチャ(L</Signatures> 参照)が有効の場合、より短い
3243PROTO 文法は利用できません; シグネチャと衝突するからです。
3244この場合、プロトタイプは属性の形式でのみ宣言できます。
3245
3246=begin original
3247
3248The
32492331function declaration must be visible at compile time. The prototype
3250affects only interpretation of regular calls to the function,
2332affects only interpretation of new-style calls to the function,
3251where regular is defined as not using the C<&> sigil. In
2333where new-style is defined as not using the C<&> character. In
32522334other words, if you call it like a built-in function, then it behaves
3253like a built-in function. If you call it like an old-fashioned (perl4)
2335like a built-in function. If you call it like an old-fashioned
32542336subroutine, then it behaves like an old-fashioned subroutine. It
32552337naturally falls out from this rule that prototypes have no influence
32562338on subroutine references like C<\&foo> or on indirect subroutine
3257calls like C<&{$subref}()> or C<< $subref->() >>.
2339calls like C<&{$subref}> or C<< $subref->() >>.
32582340
32592341=end original
32602342
2343C<mypush()> は C<push()> が取るのとまったく同じ引数を取ります。
32612344関数宣言はコンパイル時に可視でなければなりません。
3262プロトタイプの効果は、関数を C<&> を使わない通常の呼び出しで
2345プロトタイプの効果は、関数を C<&> を使わない新しい形式の呼び出しで
32632346解釈したときのみです。
32642347言い換えれば、組み込み関数と同じように関数を呼び出せば、
32652348それは組み込み関数と同じように振る舞う、ということです。
3266古い (perl4) 形式のサブルーチンと同じように呼び出せば、それは古い形式の
2349古い形式のサブルーチンと同じように呼び出せば、それは古い形式の
32672350サブルーチンと同じように振る舞います。
3268C<\&foo> のようなサブルーチンのリファレンスや C<&{$subref}()> のような
2351C<\&foo> のようなサブルーチンのリファレンスや C<&{$subref}> のような
32692352間接的なサブルーチン呼び出し、C<< $subref->() >> に関してはプロトタイプは
32702353なんの影響も及ぼさないので、この規則から外れます。
32712354
32722355=begin original
32732356
32742357Method calls are not influenced by prototypes either, because the
32752358function to be called is indeterminate at compile time, since
32762359the exact code called depends on inheritance.
32772360
32782361=end original
32792362
32802363メソッド呼び出しはプロトタイプを行う/行わないによる影響を受けません; なぜなら
32812364正確な呼び出しコードは、継承に依存しているためにコンパイル時には
32822365不確定だからです。
32832366
32842367=begin original
32852368
32862369Because the intent of this feature is primarily to let you define
32872370subroutines that work like built-in functions, here are prototypes
32882371for some other functions that parse almost exactly like the
32892372corresponding built-in.
32902373
32912374=end original
32922375
32932376組み込み関数のように動作するサブルーチンをあなたに定義させるのが
32942377この機能の基本的な目的なので、ここで対応した組み込み関数のように
32952378解釈される幾つかの関数プロトタイプを挙げておきましょう。
32962379
32972380=begin original
32982381
3299 Declared as Called as
2382 Declared as Called as
33002383
33012384=end original
33022385
3303 宣言 呼び出し
2386 宣言 呼び出し
33042387
3305 sub mylink ($$) mylink $old, $new
2388 sub mylink ($$) mylink $old, $new
3306 sub myvec ($$$) myvec $var, $offset, 1
2389 sub myvec ($$$) myvec $var, $offset, 1
3307 sub myindex ($$;$) myindex getstring(), "substr"
2390 sub myindex ($$;$) myindex &getstring, "substr"
3308 sub mysyswrite ($$$;$) mysyswrite $buf, 0, length($buf) - $off, $off
2391 sub mysyswrite ($$$;$) mysyswrite $buf, 0, length($buf) - $off, $off
3309 sub myreverse (@) myreverse $x, $y, $z
2392 sub myreverse (@) myreverse $a, $b, $c
3310 sub myjoin ($@) myjoin ":", $x, $y, $z
2393 sub myjoin ($@) myjoin ":", $a, $b, $c
3311 sub mypop (\@) mypop @array
2394 sub mypop (+) mypop @array
3312 sub mysplice (\@$$@) mysplice @array, 0, 2, @pushme
2395 sub mysplice (+$$@) mysplice @array, 0, 2, @pushme
3313 sub mykeys (\[%@]) mykeys $hashref->%*
2396 sub mykeys (+) mykeys %{$hashref}
3314 sub myopen (*;$) myopen HANDLE, $name
2397 sub myopen (*;$) myopen HANDLE, $name
3315 sub mypipe (**) mypipe READHANDLE, WRITEHANDLE
2398 sub mypipe (**) mypipe READHANDLE, WRITEHANDLE
3316 sub mygrep (&@) mygrep { /foo/ } $x, $y, $z
2399 sub mygrep (&@) mygrep { /foo/ } $a, $b, $c
3317 sub myrand (;$) myrand 42
2400 sub myrand (;$) myrand 42
3318 sub mytime () mytime
2401 sub mytime () mytime
33192402
33202403=begin original
33212404
33222405Any backslashed prototype character represents an actual argument
33232406that must start with that character (optionally preceded by C<my>,
33242407C<our> or C<local>), with the exception of C<$>, which will
33252408accept any scalar lvalue expression, such as C<$foo = 7> or
3326C<< my_function()->[0] >>. The value passed as part of C<@_> will be a
2409C<< my_function()->[0] >>. The value passed as part of C<@_> will be a
33272410reference to the actual argument given in the subroutine call,
33282411obtained by applying C<\> to that argument.
33292412
33302413=end original
33312414
33322415バックスラッシュが付けられたプロトタイプ文字は、実引数が
33332416その文字で始まるものでなければならないことを表します
33342417(オプションとして C<my>, C<our>, C<local> が前置されます);
33352418C<$foo = 7> や C<< my_function()->[0] >> のようにマークなしでも任意の
33362419左辺値表現を受け付ける C<$> は例外です。
33372420C<@_> の一部として渡された引数は、そのサブルーチン呼び出しにおいて
33382421与えられた実引数に C<\> を適用したリファレンスとなります。
33392422
33402423=begin original
33412424
33422425You can use the C<\[]> backslash group notation to specify more than one
3343allowed argument type. For example:
2426allowed argument type. For example:
33442427
33452428=end original
33462429
33472430C<\[]> バックスラッシュ記法を、一つまたは複数の引数型を指定するために
33482431使えます。
33492432例えば:
33502433
33512434 sub myref (\[$@%&*])
33522435
33532436=begin original
33542437
33552438will allow calling myref() as
33562439
33572440=end original
33582441
33592442というのは以下のように myref() を呼び出すのを許し:
33602443
33612444 myref $var
33622445 myref @array
33632446 myref %hash
33642447 myref &sub
33652448 myref *glob
33662449
33672450=begin original
33682451
33692452and the first argument of myref() will be a reference to
3370a scalar, an array, a hash, a subroutine, or a glob.
2453a scalar, an array, a hash, a code, or a glob.
33712454
33722455=end original
33732456
3374myref() の最初の引数は スカラ、配列、ハッシュ、
2457myref() の最初の引数は スカラ、配列、ハッシュ、コード、グロブのいずれかへの
3375サブルーチン、グロブのいずれかへのリファレンスです。
2458リファレンスです。
33762459
33772460=begin original
33782461
33792462Unbackslashed prototype characters have special meanings. Any
33802463unbackslashed C<@> or C<%> eats all remaining arguments, and forces
33812464list context. An argument represented by C<$> forces scalar context. An
33822465C<&> requires an anonymous subroutine, which, if passed as the first
3383argument, may look like a bare block: It does not require the C<sub> keyword
2466argument, does not require the C<sub> keyword or a subsequent comma.
3384or a subsequent comma.
33852467
33862468=end original
33872469
33882470バックスラッシュが付けられていない文字は特別な意味を持っています。
33892471バックスラッシュを付けられていない すべての C<@> とC<%> は残りの引数全てを
33902472取ってしまい、さらにリストコンテキストを強制します。
33912473C<$> で表される引数はスカラコンテキストを強制されます。
3392C<&> は 第一引数として渡されて、裸のブロックのように見える場合、
2474第一引数として渡され場合、C<&> は C<sub> キーワードや連続したカンマを
3393無名サブルーチンを要求します:
2475要求しないような無名サブルーチンを要求します
3394これは C<sub> キーワードや連続したカンマを要求しません。
33952476
33962477=begin original
33972478
33982479A C<*> allows the subroutine to accept a bareword, constant, scalar expression,
33992480typeglob, or a reference to a typeglob in that slot. The value will be
34002481available to the subroutine either as a simple scalar, or (in the latter
34012482two cases) as a reference to the typeglob. If you wish to always convert
34022483such arguments to a typeglob reference, use Symbol::qualify_to_ref() as
34032484follows:
34042485
34052486=end original
34062487
34072488C<*> は、スロットにある裸の単語、定数、スカラ式、型グロブ、
34082489型グロブに対するリファレンスを許しています。
34092490その値はサブルーチンにとって単純なスカラとすることも
34102491型グロブに対するリファレンスにもなります。
34112492そのような引数を常に型グロブリファレンスに変換したい場合は、
34122493Symbol::qualify_to_ref() を以下のように使います:
34132494
34142495 use Symbol 'qualify_to_ref';
34152496
34162497 sub foo (*) {
3417 my $fh = qualify_to_ref(shift, caller);
2498 my $fh = qualify_to_ref(shift, caller);
3418 ...
2499 ...
34192500 }
34202501
34212502=begin original
34222503
34232504The C<+> prototype is a special alternative to C<$> that will act like
34242505C<\[@%]> when given a literal array or hash variable, but will otherwise
34252506force scalar context on the argument. This is useful for functions which
34262507should accept either a literal array or an array reference as the argument:
34272508
34282509=end original
34292510
34302511C<+> プロトタイプは C<$> の特殊な代替物で、リテラルな配列やハッシュ変数が
34312512与えられると C<\[@%]> のように動作しますが、さもなければ引数に
34322513スカラコンテキストを強制します。
34332514これは引数としてリテラルの配列または配列リファレンスのどちらかを
34342515受け付けるような関数に有用です:
34352516
34362517 sub mypush (+@) {
34372518 my $aref = shift;
34382519 die "Not an array or arrayref" unless ref $aref eq 'ARRAY';
34392520 push @$aref, @_;
34402521 }
34412522
34422523=begin original
34432524
34442525When using the C<+> prototype, your function must check that the argument
34452526is of an acceptable type.
34462527
34472528=end original
34482529
34492530関数で C<+> プロトタイプを使ったとき、引数が受け付けられる型かを
34502531チェックしなければなりません。
34512532
34522533=begin original
34532534
34542535A semicolon (C<;>) separates mandatory arguments from optional arguments.
34552536It is redundant before C<@> or C<%>, which gobble up everything else.
34562537
34572538=end original
34582539
34592540セミコロン (C<;>) は、必須の引数と省略可能な引数とを分割します。
34602541C<@> や C<%> の前ではこれは冗長です; その他のものを吸収します。
34612542
34622543=begin original
34632544
34642545As the last character of a prototype, or just before a semicolon, a C<@>
34652546or a C<%>, you can use C<_> in place of C<$>: if this argument is not
34662547provided, C<$_> will be used instead.
34672548
34682549=end original
34692550
34702551プロトタイプの最後の文字、あるいはセミコロン、C<@>、C<%> の直前に、C<$> の
34712552代わりに C<_> を使えます: 引数が与えられない場合、C<$_> が代わりに
34722553使われます。
34732554
34742555=begin original
34752556
34762557Note how the last three examples in the table above are treated
34772558specially by the parser. C<mygrep()> is parsed as a true list
34782559operator, C<myrand()> is parsed as a true unary operator with unary
34792560precedence the same as C<rand()>, and C<mytime()> is truly without
34802561arguments, just like C<time()>. That is, if you say
34812562
34822563=end original
34832564
34842565上の例の最後の三つのものは、構文解析器が特別扱いするということに
34852566注意してください。
34862567C<mygrep()> は本当のリスト演算子として解析され、C<myrand()> は C<rand()> と
34872568同じく単項演算子の優先順位を持った真の単項演算子として、
34882569そして C<mytime()> は C<time()> と同じ様な引数を取らないものとして
34892570解析されます。つまり、
34902571
34912572 mytime +2;
34922573
34932574=begin original
34942575
34952576you'll get C<mytime() + 2>, not C<mytime(2)>, which is how it would be parsed
34962577without a prototype. If you want to force a unary function to have the
34972578same precedence as a list operator, add C<;> to the end of the prototype:
34982579
34992580=end original
35002581
35012582とすると、プロトタイプなしの場合にパースされる C<mytime(2)> ではなく、
35022583C<mytime() + 2> となります。
35032584単項関数がリスト演算子と同じ優先順位を持つようにさせたいなら、プロトタイプの
35042585末尾に C<;> を追加してください:
35052586
35062587 sub mygetprotobynumber($;);
3507 mygetprotobynumber $x > $y; # parsed as mygetprotobynumber($x > $y)
2588 mygetprotobynumber $a > $b; # parsed as mygetprotobynumber($a > $b)
35082589
35092590=begin original
35102591
35112592The interesting thing about C<&> is that you can generate new syntax with it,
35122593provided it's in the initial position:
35132594X<&>
35142595
35152596=end original
35162597
35172598C<&> に関して興味深いことは、初期位置を使って新しい構文を
35182599生成できるということです:
35192600X<&>
35202601
35212602 sub try (&@) {
3522 my($try,$catch) = @_;
2603 my($try,$catch) = @_;
3523 eval { &$try };
2604 eval { &$try };
3524 if ($@) {
2605 if ($@) {
3525 local $_ = $@;
2606 local $_ = $@;
3526 &$catch;
2607 &$catch;
3527 }
2608 }
35282609 }
35292610 sub catch (&) { $_[0] }
35302611
35312612 try {
3532 die "phooey";
2613 die "phooey";
35332614 } catch {
3534 /phooey/ and print "unphooey\n";
2615 /phooey/ and print "unphooey\n";
35352616 };
35362617
35372618=begin original
35382619
35392620That prints C<"unphooey">. (Yes, there are still unresolved
35402621issues having to do with visibility of C<@_>. I'm ignoring that
35412622question for the moment. (But note that if we make C<@_> lexically
35422623scoped, those anonymous subroutines can act like closures... (Gee,
35432624is this sounding a little Lispish? (Never mind.))))
35442625
35452626=end original
35462627
35472628これは C<“unphooey”> を出力します。
35482629(そう、C<@_> の可視性に関して解決していないことがあります。
35492630現時点ではこれを無視します。
35502631(ただし、C<@_> をレキシカルスコープにすれば上記のサブルーチンはクロージャーの
35512632ように振る舞うことができます...
35522633(んー、これってちょーっと Lisp っぽいかな? (気にしないでね。))))
35532634
35542635=begin original
35552636
35562637And here's a reimplementation of the Perl C<grep> operator:
35572638X<grep>
35582639
35592640=end original
35602641
35612642以下の例は Perl の C<grep> 演算子のの再実装です:
35622643X<grep>
35632644
35642645 sub mygrep (&@) {
3565 my $code = shift;
2646 my $code = shift;
3566 my @result;
2647 my @result;
3567 foreach $_ (@_) {
2648 foreach $_ (@_) {
3568 push(@result, $_) if &$code;
2649 push(@result, $_) if &$code;
3569 }
2650 }
3570 @result;
2651 @result;
35712652 }
35722653
35732654=begin original
35742655
35752656Some folks would prefer full alphanumeric prototypes. Alphanumerics have
35762657been intentionally left out of prototypes for the express purpose of
35772658someday in the future adding named, formal parameters. The current
35782659mechanism's main goal is to let module writers provide better diagnostics
35792660for module users. Larry feels the notation quite understandable to Perl
35802661programmers, and that it will not intrude greatly upon the meat of the
35812662module, nor make it harder to read. The line noise is visually
35822663encapsulated into a small pill that's easy to swallow.
35832664
35842665=end original
35852666
35862667一部の人は、完全に英数字を使ったプロトタイプを好むかもしれません。
35872668英数字は、将来名前付き仮引数を追加するときのために意図的に使わずに
35882669残してあるのです。
35892670現時点でのプロトタイプの機構の主な目的はモジュール作者がそのユーザーに
35902671対してより良い診断メッセージを提供させるようにするためのものなのです。
35912672この記法は Perl プログラマが非常に理解しやすく、モジュールの中身に
35922673進入するようなことも読みづらくしたりすることもないと Larry は考えています。
35932674回線の雑音は飲み込みやすい小さな丸薬に視覚的に押し込められるのです。
35942675
35952676=begin original
35962677
35972678If you try to use an alphanumeric sequence in a prototype you will
35982679generate an optional warning - "Illegal character in prototype...".
35992680Unfortunately earlier versions of Perl allowed the prototype to be
36002681used as long as its prefix was a valid prototype. The warning may be
36012682upgraded to a fatal error in a future version of Perl once the
36022683majority of offending code is fixed.
36032684
36042685=end original
36052686
36062687もしプロトタイプに英数字を使おうとすると、オプションの警告
36072688"Illegal character in prototype..." が生成されます。
36082689残念ながら、過去のバージョンの Perl では、有効なプロトタイプが前置されてさえ
36092690いれば、英数字を含むプロトタイプも認められていました。
36102691この警告は、目障りなコードの大部分が修正されたなら、将来のバージョンの
36112692Perl で致命的エラーに格上げされるかもしれません。
36122693
36132694=begin original
36142695
36152696It's probably best to prototype new functions, not retrofit prototyping
36162697into older ones. That's because you must be especially careful about
36172698silent impositions of differing list versus scalar contexts. For example,
36182699if you decide that a function should take just one parameter, like this:
36192700
36202701=end original
36212702
36222703新しい関数にプロトタイプを付けるのがおそらく最善であり、古い関数に対して
36232704プロトタイプを付けることはよくありません。
36242705なぜなら、(プロトタイプを付けたことによって)リストコンテキストと
36252706スカラコンテキストを黙って変えてしまうようなことに関して
36262707特に注意しなければならないからです。
36272708たとえば以下の例のようなただ一つの引数を取ると決めた関数を考えてみましょう:
36282709
36292710 sub func ($) {
3630 my $n = shift;
2711 my $n = shift;
3631 print "you gave me $n\n";
2712 print "you gave me $n\n";
36322713 }
36332714
36342715=begin original
36352716
36362717and someone has been calling it with an array or expression
36372718returning a list:
36382719
36392720=end original
36402721
36412722そして、誰かがこの関数をリストを返すような配列や式を引数として
36422723渡したとすると:
36432724
36442725 func(@foo);
3645 func( $text =~ /\w+/g );
2726 func( split /:/ );
36462727
36472728=begin original
36482729
36492730Then you've just supplied an automatic C<scalar> in front of their
36502731argument, which can be more than a bit surprising. The old C<@foo>
36512732which used to hold one thing doesn't get passed in. Instead,
36522733C<func()> now gets passed in a C<1>; that is, the number of elements
3653in C<@foo>. And the C<m//g> gets called in scalar context so instead of a
2734in C<@foo>. And the C<split> gets called in scalar context so it
3654list of words it returns a boolean result and advances C<pos($text)>. Ouch!
2735starts scribbling on your C<@_> parameter list. Ouch!
36552736
36562737=end original
36572738
36582739自動的に C<scalar> が引数の前に(こっそりと)付けられます; これには
36592740いささかびっくりすることになるかもしれません。
36602741これまでそうであったような、要素を持った C<@foo> が渡されることはありません。
36612742その代わり、C<func()> は C<1>、つまり C<@foo> の要素の数を得るようになります。
3662そして C<m//g> はスカラコンテキストで呼び出され、
2743そして C<split> はスカラコンテキストで呼び出され、パラメータリスト
3663単語のリストの代わりに真偽値の結果を返して C<pos($text)> をめます。
2744C<@_> に落書きてしまいます。
36642745あいたた。
36652746
36662747=begin original
36672748
3668If a sub has both a PROTO and a BLOCK, the prototype is not applied
3669until after the BLOCK is completely defined. This means that a recursive
3670function with a prototype has to be predeclared for the prototype to take
3671effect, like so:
3672
3673=end original
3674
3675サブルーチンに PROTO と BLOCK の両方がある場合、プロトタイプは BLOCK が
3676完全に定義されるまで適用されません。
3677これは、プロトタイプを持つ再帰関数は、次のように、プロトタイプが
3678有効になるように事前定義する必要があります:
3679
3680 sub foo($$);
3681 sub foo($$) {
3682 foo 1, 2;
3683 }
3684
3685=begin original
3686
36872749This is all very powerful, of course, and should be used only in moderation
36882750to make the world a better place.
36892751
36902752=end original
36912753
36922754もちろんこれは十分強力なものであり、世界をより良い場所にするという目的に
36932755限って使用すべきものでしょう。
36942756
36952757=head2 Constant Functions
36962758X<constant>
36972759
36982760(定数関数)
36992761
37002762=begin original
37012763
37022764Functions with a prototype of C<()> are potential candidates for
37032765inlining. If the result after optimization and constant folding
37042766is either a constant or a lexically-scoped scalar which has no other
37052767references, then it will be used in place of function calls made
37062768without C<&>. Calls made using C<&> are never inlined. (See
3707L<constant> for an easy way to declare most constants.)
2769F<constant.pm> for an easy way to declare most constants.)
37082770
37092771=end original
37102772
37112773C<()> というプロトタイプを持った関数はインライン展開される可能性を
37122774持っています。
37132775最適化と定数畳み込み後の結果が一つの定数か、何のリファレンスも持たない
37142776レキシカルスコープのスカラであったならば、その関数が C<&> を使わずに
37152777呼びされたときに呼び出しのその場に置かれます。
37162778C<&> を使って呼び出された関数は決してインライン展開されることは
37172779ありません。
3718(ほとんどの定数を宣言するための簡単な方法は L<constant> を
2780(ほとんどの定数を宣言するための簡単な方法は F<constant.pm> を
37192781参照してください。)
37202782
37212783=begin original
37222784
37232785The following functions would all be inlined:
37242786
37252787=end original
37262788
37272789以下に挙げた関数は全てインライン展開されるでしょう:
37282790
37292791=begin original
37302792
3731 sub pi () { 3.14159 } # Not exact, but close.
2793 sub pi () { 3.14159 } # Not exact, but close.
3732 sub PI () { 4 * atan2 1, 1 } # As good as it gets,
2794 sub PI () { 4 * atan2 1, 1 } # As good as it gets,
3733 # and it's inlined, too!
2795 # and it's inlined, too!
3734 sub ST_DEV () { 0 }
2796 sub ST_DEV () { 0 }
3735 sub ST_INO () { 1 }
2797 sub ST_INO () { 1 }
37362798
37372799=end original
37382800
3739 sub pi () { 3.14159 } # 正確ではないが近い。
2801 sub pi () { 3.14159 } # 正確ではないが近い。
3740 sub PI () { 4 * atan2 1, 1 } # 可能な限り良いもの
2802 sub PI () { 4 * atan2 1, 1 } # 可能な限り良いもの
3741 # そしてこれも展開されます!
2803 # そしてこれも展開されます!
3742 sub ST_DEV () { 0 }
2804 sub ST_DEV () { 0 }
3743 sub ST_INO () { 1 }
2805 sub ST_INO () { 1 }
37442806
3745 sub FLAG_FOO () { 1 << 8 }
2807 sub FLAG_FOO () { 1 << 8 }
3746 sub FLAG_BAR () { 1 << 9 }
2808 sub FLAG_BAR () { 1 << 9 }
3747 sub FLAG_MASK () { FLAG_FOO | FLAG_BAR }
2809 sub FLAG_MASK () { FLAG_FOO | FLAG_BAR }
37482810
3749 sub OPT_BAZ () { not (0x1B58 & FLAG_MASK) }
2811 sub OPT_BAZ () { not (0x1B58 & FLAG_MASK) }
37502812
37512813 sub N () { int(OPT_BAZ) / 3 }
37522814
37532815 sub FOO_SET () { 1 if FLAG_MASK & FLAG_FOO }
3754 sub FOO_SET2 () { if (FLAG_MASK & FLAG_FOO) { 1 } }
37552816
37562817=begin original
37572818
3758(Be aware that the last example was not always inlined in Perl 5.20 and
2819Be aware that these will not be inlined; as they contain inner scopes,
3759earlier, which did not behave consistently with subroutines containing
2820the constant folding doesn't reduce them to a single constant:
3760inner scopes.) You can countermand inlining by using an explicit
3761C<return>:
37622821
37632822=end original
37642823
3765(最後、Perl 5.20 以前では常にインライン展開されるわけではないことに
2824以下ものはインライン展開されないことに注意してください;
3766注意してください; スコープを持つサブルーチンは一貫し
2825より側にスコープがあるので、畳み込まれ定数が一つの定数に削減できません:
3767振る舞いをしません。)
3768インライン化は明示的な C<return> を使うことで撤回できます:
37692826
2827 sub foo_set () { if (FLAG_MASK & FLAG_FOO) { 1 } }
2828
37702829 sub baz_val () {
3771 if (OPT_BAZ) {
2830 if (OPT_BAZ) {
3772 return 23;
2831 return 23;
3773 }
2832 }
3774 else {
2833 else {
3775 return 42;
2834 return 42;
3776 }
2835 }
37772836 }
3778 sub bonk_val () { return 12345 }
37792837
37802838=begin original
37812839
3782As alluded to earlier you can also declare inlined subs dynamically at
2840If you redefine a subroutine that was eligible for inlining, you'll get
3783BEGIN time if their body consists of a lexically-scoped scalar which
2841a warning by default. (You can use this warning to tell whether or not a
3784has no other references. Only the first example here will be inlined:
2842particular subroutine is considered constant.) The warning is
2843considered severe enough not to be affected by the B<-w>
2844switch (or its absence) because previously compiled
2845invocations of the function will still be using the old value of the
2846function. If you need to be able to redefine the subroutine, you need to
2847ensure that it isn't inlined, either by dropping the C<()> prototype
2848(which changes calling semantics, so beware) or by thwarting the
2849inlining mechanism in some other way, such as
37852850
37862851=end original
37872852
3788先に暗示したように、本体がその他にリファレンスを持たないレキシカル
3789スコープのスカラで構成されている場合、BEGIN の時点でインラインサブルーチンを
3790動的に宣言することもできます。
3791ここでの最初の例のみがインライン化されます:
3792
3793 BEGIN {
3794 my $var = 1;
3795 no strict 'refs';
3796 *INLINED = sub () { $var };
3797 }
3798
3799 BEGIN {
3800 my $var = 1;
3801 my $ref = \$var;
3802 no strict 'refs';
3803 *NOT_INLINED = sub () { $var };
3804 }
3805
3806=begin original
3807
3808A not so obvious caveat with this (see [RT #79908]) is what happens if the
3809variable is potentially modifiable. For example:
3810
3811=end original
3812
3813これに関するそれほど明白でない欠陥 ([RT #79908] 参照) は、変数が
3814潜在的に変更可能であるときに起きることです。
3815例えば:
3816
3817 BEGIN {
3818 my $x = 10;
3819 *FOO = sub () { $x };
3820 $x++;
3821 }
3822 print FOO(); # printed 10 prior to 5.32.0
3823
3824=begin original
3825
3826From Perl 5.22 onwards this gave a deprecation warning, and from Perl 5.32
3827onwards it became a run-time error. Previously the variable was
3828immediately inlined, and stopped behaving like a normal lexical variable;
3829so it printed C<10>, not C<11>.
3830
3831=end original
3832
3833Perl 5.22 から、これは廃止予定警告を出力し、
3834Perl 5.32 から、致命的エラーになりました。
3835以前はこの変数は直ちにインライン化され、
3836通常のレキシカル変数のような振る舞いを止めていました;
3837従ってこれは C<11> ではなく C<10> を表示していました。
3838
3839=begin original
3840
3841If you still want such a subroutine to be inlined (with no warning), make
3842sure the variable is not used in a context where it could be modified
3843aside from where it is declared.
3844
3845=end original
3846
3847まだそのようなサブルーチンを (警告なしで) インライン化したい場合、
3848その変数が宣言された
3849場所以外で変更されるかも知れないコンテキストで使われないことを
3850確認してください。
3851
3852 # Fine, no warning
3853 BEGIN {
3854 my $x = 54321;
3855 *INLINED = sub () { $x };
3856 }
3857 # Error
3858 BEGIN {
3859 my $x;
3860 $x = 54321;
3861 *ALSO_INLINED = sub () { $x };
3862 }
3863
3864=begin original
3865
3866Perl 5.22 also introduced the "const" attribute as an alternative. It was
3867initially experimental, but made stable in Perl 5.40. When applied to an
3868anonymous subroutine, it forces the sub to be called when the C<sub>
3869expression is evaluated. The return value is captured and turned into a
3870constant subroutine:
3871
3872=end original
3873
3874Perl 5.22 ではまた代替案として "const" 属性を導入しました。
3875これは当初実験的でしたが、Perl 5.40 で安定的になりました。
3876無名サブルーチンに適用されると、サブルーチンを C<sub> 式が評価されたときの
3877呼び出しに固定します。
3878返り値は捕捉され、定数サブルーチンに変換されます:
3879
3880 my $x = 54321;
3881 *INLINED = sub : const { $x };
3882 $x++;
3883
3884=begin original
3885
3886The return value of C<INLINED> in this example will always be 54321,
3887regardless of later modifications to $x. You can also put any arbitrary
3888code inside the sub, at it will be executed immediately and its return
3889value captured the same way.
3890
3891=end original
3892
3893この例での C<INLINED> の返り値は、その後 $x が変更されても常に 54321 です。
3894また、サブルーチンの内部で任意のコードを書くことができ、直ちに実行されて
3895その返り値は同様に捕捉されます。
3896
3897=begin original
3898
3899If you really want a subroutine with a C<()> prototype that returns a
3900lexical variable you can easily force it to not be inlined by adding
3901an explicit C<return>:
3902
3903=end original
3904
3905C<()> プロトタイプを持ち、レキシカル変数を返すサブルーチンが本当にほしいなら、
3906明示的な C<return> を追加することでインライン化しないことを簡単に強制できます:
3907
3908 BEGIN {
3909 my $x = 10;
3910 *FOO = sub () { return $x };
3911 $x++;
3912 }
3913 print FOO(); # prints 11
3914
3915=begin original
3916
3917The easiest way to tell if a subroutine was inlined is by using
3918L<B::Deparse>. Consider this example of two subroutines returning
3919C<1>, one with a C<()> prototype causing it to be inlined, and one
3920without (with deparse output truncated for clarity):
3921
3922=end original
3923
3924サブルーチンがインライン化されていることを知る最も簡単な方法は
3925L<B::Deparse> によるものです。
3926C<1> を返す二つのサブルーチンの例を考えると、
3927C<()> プロトタイプを持つものはインライン化を引き起こし、もう一つは
3928引き起こしません (明確化のために deparse の出力を切り詰めています):
3929
3930 $ perl -MO=Deparse -e 'sub ONE { 1 } if (ONE) { print ONE if ONE }'
3931 sub ONE {
3932 1;
3933 }
3934 if (ONE ) {
3935 print ONE() if ONE ;
3936 }
3937
3938 $ perl -MO=Deparse -e 'sub ONE () { 1 } if (ONE) { print ONE if ONE }'
3939 sub ONE () { 1 }
3940 do {
3941 print 1
3942 };
3943
3944=begin original
3945
3946If you redefine a subroutine that was eligible for inlining, you'll
3947get a warning by default. You can use this warning to tell whether or
3948not a particular subroutine is considered inlinable, since it's
3949different than the warning for overriding non-inlined subroutines:
3950
3951=end original
3952
39532853インライン展開するのに適切であったサブルーチンを再定義するとデフォルトでは
39542854警告を受けることになります。
3955この警告を、あるサブルーチンがライン化可能と認識されるかどうかを
2855(この警告を、あるサブルーチンが定数サブルーチンとして認識されるかどうかを
3956区別するために使うことができます; これはインライン化されていないサブルーチンを
2856区別するために使うことができます。)
3957オーバーラドすることによる警告とは異なります:
2857以前にコンパルした関数の起動によってこの関数の古い値を使い続けので、
3958
3959 $ perl -e 'sub one () {1} sub one () {2}'
3960 Constant subroutine one redefined at -e line 1.
3961 $ perl -we 'sub one {1} sub one {2}'
3962 Subroutine one redefined at -e line 1.
3963
3964=begin original
3965
3966The warning is considered severe enough not to be affected by the
3967B<-w> switch (or its absence) because previously compiled invocations
3968of the function will still be using the old value of the function. If
3969you need to be able to redefine the subroutine, you need to ensure
3970that it isn't inlined, either by dropping the C<()> prototype (which
3971changes calling semantics, so beware) or by thwarting the inlining
3972mechanism in some other way, e.g. by adding an explicit C<return>, as
3973mentioned above:
3974
3975=end original
3976
39772858この警告は B<-w> オプション(またはそれがないこと)に影響を受けるものに
39782859するには重大すぎると考えられました。
39792860そのサブルーチンを再定義できる必要があるのならば、C<()> プロトタイプを
39802861やめる(これは呼び出しのセマンティクスを変えてしまうので注意してください)か、
3981方法、えば上述のように示的な C<return> の追加によっ
2862以下の例のようにインライン展開機構を
3982インライン展開機構を働かせないようにしてサブルーチンが
2863働かせないようにしてサブルーチンがインライン展開されていないことを
3983インライン展開されていないことを保証する必要があります:
2864保証する必要があります
39842865
3985 sub not_inlined () { return 23 }
2866 sub not_inlined () {
2867 23 if $];
2868 }
39862869
39872870=head2 Overriding Built-in Functions
39882871X<built-in> X<override> X<CORE> X<CORE::GLOBAL>
39892872
39902873(組み込み関数のオーバーライド)
39912874
39922875=begin original
39932876
39942877Many built-in functions may be overridden, though this should be tried
39952878only occasionally and for good reason. Typically this might be
39962879done by a package attempting to emulate missing built-in functionality
39972880on a non-Unix system.
39982881
39992882=end original
40002883
40012884多くの組み込み関数はオーバーライドすることができます; ただし、これを行うのは、
40022885そうする理由と状況とがあるときのみに限るべきでしょう。
40032886これが行われる典型的な例は、非 UNIX システムにおいて欠けている組み込み機能を
40042887エミュレートするためにパッケージを使おうとする場合でしょう。
40052888
40062889=begin original
40072890
40082891Overriding may be done only by importing the name from a module at
40092892compile time--ordinary predeclaration isn't good enough. However, the
40102893C<use subs> pragma lets you, in effect, predeclare subs
40112894via the import syntax, and these names may then override built-in ones:
40122895
40132896=end original
40142897
40152898オーバーライドはコンパイル時にモジュールからのみ名前を import できます--
40162899通常の先行宣言では十分ではありません。
40172900しかしながら、C<use subs> プラグマは import 構文を通して先行宣言を行い、
40182901さらにそれらの名前が組み込みのものをオーバーライドできるようにします:
40192902
40202903 use subs 'chdir', 'chroot', 'chmod', 'chown';
40212904 chdir $somewhere;
40222905 sub chdir { ... }
40232906
40242907=begin original
40252908
40262909To unambiguously refer to the built-in form, precede the
40272910built-in name with the special package qualifier C<CORE::>. For example,
40282911saying C<CORE::open()> always refers to the built-in C<open()>, even
40292912if the current package has imported some other subroutine called
40302913C<&open()> from elsewhere. Even though it looks like a regular
4031function call, it isn't: the C<CORE::> prefix in that case is part of Perl's
2914function call, it isn't: the CORE:: prefix in that case is part of Perl's
4032syntax, and works for any keyword, regardless of what is in the C<CORE>
2915syntax, and works for any keyword, regardless of what is in the CORE
40332916package. Taking a reference to it, that is, C<\&CORE::open>, only works
40342917for some keywords. See L<CORE>.
40352918
40362919=end original
40372920
40382921曖昧さなく組み込みのものを参照するために、特別なパッケージ修飾子
40392922C<CORE::> を組み込みの名前に前置することができます。
40402923たとえば C<CORE::open()> とすると、たとえカレントパッケージが
40412924C<&open()> といった別のサブルーチンを import していたとしても
40422925これは常に組み込み関数の C<open()> を参照します。
40432926これは通常の関数呼び出しのように見えますが、そうではありません:
4044この場合の C<CORE::> 接頭辞は Perl の文法の一部で、C<CORE> パッケージに
2927この場合の CORE:: 接頭辞は Perl の文法の一部で、CORE パッケージに何があるか
4045何があるかに関わらず、どのようなキーワードでも動作します。
2928関わらず、どのようなキーワードでも動作します。
40462929C<\&CORE::open> のように、これに対するリファレンスの取得は、一部の
40472930キーワードでのみ動作します。
40482931L<CORE> を参照してください。
40492932
40502933=begin original
40512934
40522935Library modules should not in general export built-in names like C<open>
40532936or C<chdir> as part of their default C<@EXPORT> list, because these may
40542937sneak into someone else's namespace and change the semantics unexpectedly.
40552938Instead, if the module adds that name to C<@EXPORT_OK>, then it's
40562939possible for a user to import the name explicitly, but not implicitly.
40572940That is, they could say
40582941
40592942=end original
40602943
40612944ライブラリモジュールは、C<open> だとか C<chdir> のような組み込みの名前を
40622945デフォルトの C<@EXPORT> リストの一部としてexport すべきではありません;
40632946なぜなら、ライブラリを使った人の名前空間を汚し、予期しない動作を
40642947呼び起こす可能性があるからです。
40652948C<@EXPORT_OK> に名前を追加すれば、ユーザーがその名前を陽に指定すれば
40662949import することができ、暗黙の内に import されてしまうことはありません。
40672950つまり、以下のようにすると
40682951
40692952 use Module 'open';
40702953
40712954=begin original
40722955
40732956and it would import the C<open> override. But if they said
40742957
40752958=end original
40762959
40772960C<open()> のオーバーライドをインポートします。
40782961しかし、以下のようにすると
40792962
40802963 use Module;
40812964
40822965=begin original
40832966
40842967they would get the default imports without overrides.
40852968
40862969=end original
40872970
40882971デフォルトのインポートを行い、オーバーライドはしません。
40892972
40902973=begin original
40912974
40922975The foregoing mechanism for overriding built-in is restricted, quite
40932976deliberately, to the package that requests the import. There is a second
40942977method that is sometimes applicable when you wish to override a built-in
40952978everywhere, without regard to namespace boundaries. This is achieved by
40962979importing a sub into the special namespace C<CORE::GLOBAL::>. Here is an
40972980example that quite brazenly replaces the C<glob> operator with something
40982981that understands regular expressions.
40992982
41002983=end original
41012984
41022985組み込みのものに対するオーバーライディングのための機構は
41032986インポートを要求したパッケージに制限されています。
41042987名前空間に関係なく組み込みの任意のものをオーバーライドしたいと
41052988考えたときに使えることもある二番目の方法があります。
41062989それは特殊な名前空間 C<CORE::GLOBAL> に対して sub を
41072990インポートすることによるものです。
41082991以下にちょっとした正規表現を使って C<glob> 演算子を置き換える例を挙げます。
41092992
41102993 package REGlob;
41112994 require Exporter;
41122995 @ISA = 'Exporter';
41132996 @EXPORT_OK = 'glob';
41142997
41152998 sub import {
4116 my $pkg = shift;
2999 my $pkg = shift;
4117 return unless @_;
3000 return unless @_;
4118 my $sym = shift;
3001 my $sym = shift;
4119 my $where = ($sym =~ s/^GLOBAL_// ? 'CORE::GLOBAL' : caller(0));
3002 my $where = ($sym =~ s/^GLOBAL_// ? 'CORE::GLOBAL' : caller(0));
4120 $pkg->export($where, $sym, @_);
3003 $pkg->export($where, $sym, @_);
41213004 }
41223005
41233006 sub glob {
4124 my $pat = shift;
3007 my $pat = shift;
4125 my @got;
3008 my @got;
4126 if (opendir my $d, '.') {
3009 if (opendir my $d, '.') {
4127 @got = grep /$pat/, readdir $d;
3010 @got = grep /$pat/, readdir $d;
4128 closedir $d;
3011 closedir $d;
4129 }
3012 }
4130 return @got;
3013 return @got;
41313014 }
41323015 1;
41333016
41343017=begin original
41353018
41363019And here's how it could be (ab)used:
41373020
41383021=end original
41393022
41403023そして以下は悪い使い方(かもしれない)例です:
41413024
4142 #use REGlob 'GLOBAL_glob'; # override glob() in ALL namespaces
3025 #use REGlob 'GLOBAL_glob'; # override glob() in ALL namespaces
41433026 package Foo;
4144 use REGlob 'glob'; # override glob() in Foo:: only
3027 use REGlob 'glob'; # override glob() in Foo:: only
4145 print for <^[a-z_]+\.pm\$>; # show all pragmatic modules
3028 print for <^[a-z_]+\.pm\$>; # show all pragmatic modules
41463029
41473030=begin original
41483031
41493032The initial comment shows a contrived, even dangerous example.
41503033By overriding C<glob> globally, you would be forcing the new (and
41513034subversive) behavior for the C<glob> operator for I<every> namespace,
41523035without the complete cognizance or cooperation of the modules that own
41533036those namespaces. Naturally, this should be done with extreme caution--if
41543037it must be done at all.
41553038
41563039=end original
41573040
41583041最初のコメント部分は不自然で、危険ですらある例です。
41593042グローバルに C<glob> をオーバーライドすることによって、
41603043完全に認識されていなかったりモジュール固有の名前空間との協調を
41613044考慮せずに、C<glob> の動作が I<全ての>
41623045名前空間で強制的に新しい(そして破壊的な)ものになります。
41633046こういったことは(それが本当にやらなければいけないこととした上で)
41643047大いに注意したうえで行うべきものです。
41653048
41663049=begin original
41673050
41683051The C<REGlob> example above does not implement all the support needed to
4169cleanly override Perl's C<glob> operator. The built-in C<glob> has
3052cleanly override perl's C<glob> operator. The built-in C<glob> has
41703053different behaviors depending on whether it appears in a scalar or list
4171context, but our C<REGlob> doesn't. Indeed, many Perl built-ins have such
3054context, but our C<REGlob> doesn't. Indeed, many perl built-in have such
41723055context sensitive behaviors, and these must be adequately supported by
41733056a properly written override. For a fully functional example of overriding
41743057C<glob>, study the implementation of C<File::DosGlob> in the standard
41753058library.
41763059
41773060=end original
41783061
4179前述の C<REGlob> の例は、Perl の C<glob> 演算子をオーバーライドするのに
3062前述の C<REGlob> の例は、perl の C<glob> 演算子をオーバーライドするのに
41803063必要な全てのことを実装してはいません。
41813064組み込みの C<glob> はそれがスカラコンテキストで使われたのか
41823065リストコンテキストで使われたのかによって異なる動作をしますが、
41833066先程の例の C<REGlob> ではそうなっていません。
4184Perl の組み込みのものの多くがこのようにコンテキストによって違う動作をし、
3067perl の組み込みのものの多くがこのようにコンテキストによって違う動作をし、
41853068オーバーライドするものを記述する場合にはきちんとそれを
41863069サポートしていなければなりません。
41873070C<glob> のオーバーライディングの完全版は、
41883071標準ライブラリにある C<File::DosGlob> の実装で勉強してください。
41893072
41903073=begin original
41913074
41923075When you override a built-in, your replacement should be consistent (if
41933076possible) with the built-in native syntax. You can achieve this by using
41943077a suitable prototype. To get the prototype of an overridable built-in,
41953078use the C<prototype> function with an argument of C<"CORE::builtin_name">
41963079(see L<perlfunc/prototype>).
41973080
41983081=end original
41993082
42003083組み込み関数をオーバーライドするとき、オーバーライドした関数は
42013084組み込み関数の元の文法(もしあれば)と一貫しているべきです。
42023085これは適切なプロトタイプを使うことで達成できます。
42033086オーバーライドできる組み込み関数のプロトタイプを得るためには、
42043087C<"CORE::builtin_name"> を引き数として C<prototype> 関数を使ってください
42053088(L<perlfunc/prototype> を参照してください)。
42063089
42073090=begin original
42083091
42093092Note however that some built-ins can't have their syntax expressed by a
42103093prototype (such as C<system> or C<chomp>). If you override them you won't
42113094be able to fully mimic their original syntax.
42123095
42133096=end original
42143097
42153098(C<system> や C<chomp> のように)文法をプロトタイプで表現できない
42163099組み込み関数に注意してください。
42173100もしこれらをオーバーライドすると、もとの文法を完全に真似ることは
42183101できません。
42193102
42203103=begin original
42213104
42223105The built-ins C<do>, C<require> and C<glob> can also be overridden, but due
42233106to special magic, their original syntax is preserved, and you don't have
42243107to define a prototype for their replacements. (You can't override the
42253108C<do BLOCK> syntax, though).
42263109
42273110=end original
42283111
42293112組み込みの C<do>, C<require>, C<glob> もオーバーライドできますが、特別な
42303113魔法によって、これらの元の文法は保存され、オーバーライドしたもののために
42313114プロトタイプを定義する必要はありません。
42323115(しかし、C<do BLOCK> 文法はオーバーライドできません)。
42333116
42343117=begin original
42353118
42363119C<require> has special additional dark magic: if you invoke your
42373120C<require> replacement as C<require Foo::Bar>, it will actually receive
42383121the argument C<"Foo/Bar.pm"> in @_. See L<perlfunc/require>.
42393122
42403123=end original
42413124
42423125C<require> は特別な追加の黒魔法を持ちます: C<require> をオーバーライドした
42433126ものを C<require Foo::Bar> として起動すると、実際には @_ に引き数として
42443127C<"Foo/Bar.pm"> を受け取ります。
42453128L<perlfunc/require> を参照してください。
42463129
42473130=begin original
42483131
42493132And, as you'll have noticed from the previous example, if you override
42503133C<glob>, the C<< <*> >> glob operator is overridden as well.
42513134
42523135=end original
42533136
42543137そして、以前の例から気付いたかもしれませんが、もし C<glob> を
42553138オーバーライドすると、グロブ演算子 C<< <*> >> もオーバーライドされます。
42563139
42573140=begin original
42583141
42593142In a similar fashion, overriding the C<readline> function also overrides
4260the equivalent I/O operator C<< <FILEHANDLE> >>. Also, overriding
3143the equivalent I/O operator C<< <FILEHANDLE> >>. Also, overriding
42613144C<readpipe> also overrides the operators C<``> and C<qx//>.
42623145
42633146=end original
42643147
42653148同様に、C<readline> 関数をオーバーライドすると 等価な
42663149I/O 演算子である C<< <FILEHANDLE> >> もオーバーライドします。
42673150また、C<readpipe> をオーバーライドすると、演算子 C<``> と C<qx//> も
42683151オーバーライドします。
42693152
42703153=begin original
42713154
42723155Finally, some built-ins (e.g. C<exists> or C<grep>) can't be overridden.
42733156
42743157=end original
42753158
42763159最後に、いくつかの組み込み関数(C<exists> や C<grep>) は
42773160オーバーライドできません。
42783161
42793162=head2 Autoloading
42803163X<autoloading> X<AUTOLOAD>
42813164
42823165(オートロード)
42833166
42843167=begin original
42853168
42863169If you call a subroutine that is undefined, you would ordinarily
42873170get an immediate, fatal error complaining that the subroutine doesn't
42883171exist. (Likewise for subroutines being used as methods, when the
42893172method doesn't exist in any base class of the class's package.)
42903173However, if an C<AUTOLOAD> subroutine is defined in the package or
42913174packages used to locate the original subroutine, then that
42923175C<AUTOLOAD> subroutine is called with the arguments that would have
42933176been passed to the original subroutine. The fully qualified name
42943177of the original subroutine magically appears in the global $AUTOLOAD
42953178variable of the same package as the C<AUTOLOAD> routine. The name
42963179is not passed as an ordinary argument because, er, well, just
42973180because, that's why. (As an exception, a method call to a nonexistent
42983181C<import> or C<unimport> method is just skipped instead. Also, if
42993182the AUTOLOAD subroutine is an XSUB, there are other ways to retrieve the
43003183subroutine name. See L<perlguts/Autoloading with XSUBs> for details.)
43013184
43023185=end original
43033186
43043187定義されていないサブルーチンを呼び出した場合、通常はそんなサブルーチンは
43053188ないといった内容のエラーが即座に発生するでしょう(メソッドとして
43063189使われているサブルーチンも同様に、メソッドがそのクラスのパッケージの
43073190すべての基底クラス中に存在していなかったとき)。
43083191しかし、C<AUTOLOAD> サブルーチンがそのパッケージの中で定義されているか
43093192元のサブルーチンで使われるパッケージの中で定義されていれば、
43103193元のサブルーチンに対して渡されたであろう引数を伴ってその
43113194C<AUTOLOAD> サブルーチンが呼び出されます。
43123195元のサブルーチンの完全修飾された名前は C<AUTOLOAD> ルーチンと同じ
43133196パッケージのグローバルな変数 $AUTOLOAD の中に現れます。
43143197この名前は通常の引数として渡されることはありません。
43153198なぜなら、その、あー、なんというかこれが理由です。
43163199(例外として、存在しない C<import> か C<unimport> メソッドへの呼び出しは
43173200単に無視されます。
43183201また、AUTOLOAD サブルーチンが XSUB なら、サブルーチン名を取得するための
43193202その他の方法があります。
43203203詳しくは L<perlguts/Autoloading with XSUBs> を参照してください。)
43213204
43223205=begin original
43233206
43243207Many C<AUTOLOAD> routines load in a definition for the requested
43253208subroutine using eval(), then execute that subroutine using a special
43263209form of goto() that erases the stack frame of the C<AUTOLOAD> routine
43273210without a trace. (See the source to the standard module documented
43283211in L<AutoLoader>, for example.) But an C<AUTOLOAD> routine can
43293212also just emulate the routine and never define it. For example,
43303213let's pretend that a function that wasn't defined should just invoke
43313214C<system> with those arguments. All you'd do is:
43323215
43333216=end original
43343217
43353218多くの C<AUTOLOAD> ルーチンは eval() を使った要求サブルーチンに
43363219対する定義でロードされ、C<AUTOLOAD> ルーチンのスタックフレームを
43373220トレースなしに消してしまうような特別な形式の goto() を使うサブルーチンを
43383221実行します。
43393222(実例は標準の C<AutoLoader> モジュールのソースを参照してください。)
43403223しかし、C<AUTOLOAD> ルーチンはそのようなルーチンの模倣をすることもできて、
43413224かつそれを定義しません。
43423225たとえば、定義されてない関数があったときに、それを引数として
43433226C<system()> を起動するようにさせます。
43443227あなたがやろうとしていることはこういうことです:
43453228
43463229 sub AUTOLOAD {
4347 our $AUTOLOAD; # keep 'use strict' happy
3230 my $program = $AUTOLOAD;
4348 my $program = $AUTOLOAD;
3231 $program =~ s/.*:://;
4349 $program =~ s/.*:://;
3232 system($program, @_);
4350 system($program, @_);
43513233 }
43523234 date();
4353 who();
3235 who('am', 'i');
43543236 ls('-l');
43553237
43563238=begin original
43573239
43583240In fact, if you predeclare functions you want to call that way, you don't
43593241even need parentheses:
43603242
43613243=end original
43623244
43633245このやり方で呼び出したい関数を先行宣言しておけば、括弧すら
43643246必要ではなくなります。
43653247
43663248 use subs qw(date who ls);
43673249 date;
4368 who;
3250 who "am", "i";
43693251 ls '-l';
43703252
43713253=begin original
43723254
43733255A more complete example of this is the Shell module on CPAN, which
43743256can treat undefined subroutine calls as calls to external programs.
43753257
43763258=end original
43773259
43783260この例のもっと完全なものが、CPAN にある Shell モジュールです; これは
43793261未定義のサブルーチンの呼び出しを外部プログラムの呼び出しとして扱います。
43803262
43813263=begin original
43823264
43833265Mechanisms are available to help modules writers split their modules
43843266into autoloadable files. See the standard AutoLoader module
43853267described in L<AutoLoader> and in L<AutoSplit>, the standard
43863268SelfLoader modules in L<SelfLoader>, and the document on adding C
43873269functions to Perl code in L<perlxs>.
43883270
43893271=end original
43903272
43913273この仕掛けは、モジュール作者がモジュールを自動ロード可能なファイルに
43923274分割するのを助けるために使用可能です。
43933275L<AutoLoader> と L<AutoSplit> で説明されている
43943276標準の AutoLoader モジュールと、L<SelfLoader> で説明されている
43953277標準の SelfLoader モジュール、そして L<perlxs> にある Perl プログラムに
43963278C の関数を追加することに関するドキュメントを参照してください。
43973279
43983280=head2 Subroutine Attributes
43993281X<attribute> X<subroutine, attribute> X<attrs>
44003282
44013283(サブルーチン属性)
44023284
44033285=begin original
44043286
44053287A subroutine declaration or definition may have a list of attributes
44063288associated with it. If such an attribute list is present, it is
44073289broken up at space or colon boundaries and treated as though a
44083290C<use attributes> had been seen. See L<attributes> for details
44093291about what attributes are currently supported.
44103292Unlike the limitation with the obsolescent C<use attrs>, the
44113293C<sub : ATTRLIST> syntax works to associate the attributes with
44123294a pre-declaration, and not just with a subroutine definition.
44133295
44143296=end original
44153297
44163298サブルーチン宣言や定義には、それと結び付けられた属性のリストを
44173299持たせることが出来ます。
44183300このような属性が合った場合、スペースかコロンを区切りとして分割され、
44193301C<use attributes> があったかのように扱われます。
44203302属性が現在対応している詳細については L<attributes> を参照してください。
44213303古い C<use attrs> の制限と違って、C<sub : ATTRLIST> の文法は
44223304前方宣言でも動作し、サブルーチン定義だけではありません。
44233305
44243306=begin original
44253307
44263308The attributes must be valid as simple identifier names (without any
44273309punctuation other than the '_' character). They may have a parameter
44283310list appended, which is only checked for whether its parentheses ('(',')')
44293311nest properly.
44303312
44313313=end original
44323314
44333315属性は単純な識別子名('_' 以外の句読点なし)でなければなりません。
44343316パラメータリストを追加するときに、括弧('(',')')のネストが
44353317正しいかどうかだけをチェックします。
44363318
44373319=begin original
44383320
44393321Examples of valid syntax (even though the attributes are unknown):
44403322
44413323=end original
44423324
44433325(属性が不明だとしても)正常な文法の例です:
44443326
44453327 sub fnord (&\%) : switch(10,foo(7,3)) : expensive;
44463328 sub plugh () : Ugly('\(") :Bad;
44473329 sub xyzzy : _5x5 { ... }
44483330
44493331=begin original
44503332
44513333Examples of invalid syntax:
44523334
44533335=end original
44543336
44553337不正な文法の例です:
44563338
4457 sub fnord : switch(10,foo(); # ()-string not balanced
3339 sub fnord : switch(10,foo(); # ()-string not balanced
4458 sub snoid : Ugly('('); # ()-string not balanced
3340 sub snoid : Ugly('('); # ()-string not balanced
4459 sub xyzzy : 5x5; # "5x5" not a valid identifier
3341 sub xyzzy : 5x5; # "5x5" not a valid identifier
4460 sub plugh : Y2::north; # "Y2::north" not a simple identifier
3342 sub plugh : Y2::north; # "Y2::north" not a simple identifier
4461 sub snurt : foo + bar; # "+" not a colon or space
3343 sub snurt : foo + bar; # "+" not a colon or space
44623344
44633345=begin original
44643346
44653347The attribute list is passed as a list of constant strings to the code
44663348which associates them with the subroutine. In particular, the second example
44673349of valid syntax above currently looks like this in terms of how it's
44683350parsed and invoked:
44693351
44703352=end original
44713353
44723354属性リストはサブルーチンと結び付けられたコードに定数文字列の
44733355リストとして渡されます。
44743356特に、上記の有効な文法の第二の例では、どのようにパースと起動が
44753357行われるかという点においては以下のようになります:
44763358
44773359 use attributes __PACKAGE__, \&plugh, q[Ugly('\(")], 'Bad';
44783360
44793361=begin original
44803362
44813363For further details on attribute lists and their manipulation,
44823364see L<attributes> and L<Attribute::Handlers>.
44833365
44843366=end original
44853367
44863368属性リストとその操作に関するさらなる詳細については、
44873369L<attributes> を参照してください。
44883370
44893371=head1 SEE ALSO
44903372
44913373=begin original
44923374
44933375See L<perlref/"Function Templates"> for more about references and closures.
4494See L<perlxs> if you'd like to learn about calling C subroutines from Perl.
3376See L<perlxs> if you'd like to learn about calling C subroutines from Perl.
4495See L<perlembed> if you'd like to learn about calling Perl subroutines from C.
3377See L<perlembed> if you'd like to learn about calling Perl subroutines from C.
44963378See L<perlmod> to learn about bundling up your functions in separate files.
44973379See L<perlmodlib> to learn what library modules come standard on your system.
44983380See L<perlootut> to learn how to make object method calls.
44993381
45003382=end original
45013383
45023384リファレンスとクロージャーについては L<perlref/"Function Templates"> を
45033385参照してください。
45043386Perl から C のサブルーチンを呼び出すことに関して知りたければ、
45053387L<perlxs>を参照してください。
45063388Perl のサブルーチンを C から呼び出したい場合は L<perlembed> を参照してください。
45073389自分の関数を別のファイルで構築することに関しては L<perlmod> を参照してください。
45083390どのライブラリモジュールがあなたのシステムで標準となっているかを
45093391学ぶためには L<perlmodlib> を参照してください。
45103392オブジェクトメソッド呼び出しの作り方を学ぶには L<perlootut> を
45113393参照してください。
45123394
45133395=begin meta
45143396
45153397Translate: KIMURA Koichi (5.005_03)
45163398Update: SHIRAKATA Kentaro <argrath@ub32.org> (5.6.1-)
45173399Status: completed
45183400
45193401=end meta