/
perlsub.pod
executable file
·3372 lines (2432 loc) · 104 KB
/
perlsub.pod
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=encoding euc-jp
=head1 NAME
X<subroutine> X<function>
=begin original
perlsub - Perl subroutines
=end original
perlsub - Perl のサブルーチン
=head1 SYNOPSIS
=begin original
To declare subroutines:
X<subroutine, declaration> X<sub>
=end original
サブルーチンを宣言するには:
X<subroutine, declaration> X<sub>
=begin original
sub NAME; # A "forward" declaration.
sub NAME(PROTO); # ditto, but with prototypes
sub NAME : ATTRS; # with attributes
sub NAME(PROTO) : ATTRS; # with attributes and prototypes
=end original
sub NAME; # "先行" 宣言
sub NAME(PROTO); # 同上。ただしプロトタイプ付き
sub NAME : ATTRS; # 属性付き
sub NAME(PROTO) : ATTRS; # 属性とプロトタイプ付き
=begin original
sub NAME BLOCK # A declaration and a definition.
sub NAME(PROTO) BLOCK # ditto, but with prototypes
sub NAME : ATTRS BLOCK # with attributes
sub NAME(PROTO) : ATTRS BLOCK # with prototypes and attributes
=end original
sub NAME BLOCK # 宣言と定義
sub NAME(PROTO) BLOCK # 同上。ただしプロトタイプ付き
sub NAME : ATTRS BLOCK # 属性付き
sub NAME(PROTO) : ATTRS BLOCK # プロトタイプと属性付き
=begin original
To define an anonymous subroutine at runtime:
X<subroutine, anonymous>
=end original
実行時に無名サブルーチンを定義するには:
X<subroutine, anonymous>
=begin original
$subref = sub BLOCK; # no proto
$subref = sub (PROTO) BLOCK; # with proto
$subref = sub : ATTRS BLOCK; # with attributes
$subref = sub (PROTO) : ATTRS BLOCK; # with proto and attributes
=end original
$subref = sub BLOCK; # プロトタイプなし
$subref = sub (PROTO) BLOCK; # プロトタイプ付き
$subref = sub : ATTRS BLOCK; # 属性付き
$subref = sub (PROTO) : ATTRS BLOCK; # プロトタイプと属性付き
=begin original
To import subroutines:
X<import>
=end original
サブルーチンをインポートするには:
X<import>
use MODULE qw(NAME1 NAME2 NAME3);
=begin original
To call subroutines:
X<subroutine, call> X<call>
=end original
サブルーチンを呼び出すには:
X<subroutine, call> X<call>
=begin original
NAME(LIST); # & is optional with parentheses.
NAME LIST; # Parentheses optional if predeclared/imported.
&NAME(LIST); # Circumvent prototypes.
&NAME; # Makes current @_ visible to called subroutine.
=end original
NAME(LIST); # かっこが付いているときは & は省略可能。
NAME LIST; # 予め宣言/インポートされているならかっこは省略可能。
&NAME(LIST); # プロトタイプを回避する。
&NAME; # 呼び出されたサブルーチンから現在の @_ を可視化する。
=head1 DESCRIPTION
=begin original
Like many languages, Perl provides for user-defined subroutines.
These may be located anywhere in the main program, loaded in from
other files via the C<do>, C<require>, or C<use> keywords, or
generated on the fly using C<eval> or anonymous subroutines.
You can even call a function indirectly using a variable containing
its name or a CODE reference.
=end original
多くの言語と同様、Perl はユーザー定義のサブルーチンを提供しています。
これらのサブルーチンは、メインプログラムのどこにでも置くことができ、
C<do>, C<require>, C<use> といったキーワードを使って他のファイルから
ロードすることができ、C<eval> や無名サブルーチンを使って
生成することもできます。
サブルーチンの名前や、コードリファレンスを保持する変数を使って
間接的に関数を呼び出すことも可能です。
=begin original
The Perl model for function call and return values is simple: all
functions are passed as parameters one single flat list of scalars, and
all functions likewise return to their caller one single flat list of
scalars. Any arrays or hashes in these call and return lists will
collapse, losing their identities--but you may always use
pass-by-reference instead to avoid this. Both call and return lists may
contain as many or as few scalar elements as you'd like. (Often a
function without an explicit return statement is called a subroutine, but
there's really no difference from Perl's perspective.)
X<subroutine, parameter> X<parameter>
=end original
Perl での関数呼び出しと戻り値のモデルは単純です。全ての関数は引数を、
平坦で一つのスカラのリストで受け取り、同様に全ての関数は呼び出し元に
対して平坦で一つのスカラのりストで返すというものです。
これらの呼び出しリストと戻り値リストにある全ての配列とハッシュは、
潰されてそのアイデンティティを失います。
しかし、これを避けるために常にリファレンスで渡すことができます。
呼び出しリストと戻り値リストの両方とも好きなだけの数のスカラを
保持することができます(明確な return 文のない関数はしばしばサブルーチンと
呼ばれますが、Perl の定義上はこれらの間に何の違いもありません)。
=begin original
Any arguments passed in show up in the array C<@_>. Therefore, if
you called a function with two arguments, those would be stored in
C<$_[0]> and C<$_[1]>. The array C<@_> is a local array, but its
elements are aliases for the actual scalar parameters. In particular,
if an element C<$_[0]> is updated, the corresponding argument is
updated (or an error occurs if it is not updatable). If an argument
is an array or hash element which did not exist when the function
was called, that element is created only when (and if) it is modified
or a reference to it is taken. (Some earlier versions of Perl
created the element whether or not the element was assigned to.)
Assigning to the whole array C<@_> removes that aliasing, and does
not update any arguments.
X<subroutine, argument> X<argument> X<@_>
=end original
ルーチンに渡されるすべての引数は配列 C<@_> に置かれます。
したがって、ある関数を二つの引数を付けて呼び出したならば、
その引数は C<$_[0]> と C<$_[1]> に格納されます。
配列 C<@_> は local 配列ですが、その要素は実際の
スカラパラメータの別名です。
たとえば C<$_[0]> が更新された場合、対応する引数が更新されます
(更新できない場合にはエラーとなります)。
引数が、配列やハッシュの(関数が呼び出された時点では存在してない)
要素であった場合、その要素は(対応する別名が)修正されたり
リファレンスが取られたときにのみ作成されます(以前の一部のバージョンの
Perl では、この要素は代入が行われようが行われまいが作成されていました)。
配列 C<@_> 全体に対する代入は別名を破棄し、何の引数も更新しません。
X<subroutine, argument> X<argument> X<@_>
=begin original
A C<return> statement may be used to exit a subroutine, optionally
specifying the returned value, which will be evaluated in the
appropriate context (list, scalar, or void) depending on the context of
the subroutine call. If you specify no return value, the subroutine
returns an empty list in list context, the undefined value in scalar
context, or nothing in void context. If you return one or more
aggregates (arrays and hashes), these will be flattened together into
one large indistinguishable list.
=end original
サブルーチンから脱出するために使われた C<return> 文が
使われることもありますし、サブルーチン呼び出しのコンテキストによって
適切なコンテキスト(リスト、スカラ、無効)で評価される戻り値の指定を
省略する事が可能です。
もし何の戻り値も指定しなければ、サブルーチンはリストコンテキストにおいては
空リストを返し、スカラコンテキストにおいては未定義値を返し、
無効コンテキストではなにも返しません。
=begin original
If no C<return> is found and if the last statement is an expression, its
value is returned. If the last statement is a loop control structure
like a C<foreach> or a C<while>, the returned value is unspecified. The
empty sub returns the empty list.
X<subroutine, return value> X<return value> X<return>
=end original
C<return> がなく、最後の文が式だった場合、その値が返されます。
最後の文が C<foreach> や C<while> のようなループ制御構造だった場合、
返される値は不定です。
空のサブルーチンは空リストを返します。
X<subroutine, return value> X<return value> X<return>
=begin original
Perl does not have named formal parameters. In practice all you
do is assign to a C<my()> list of these. Variables that aren't
declared to be private are global variables. For gory details
on creating private variables, see L<"Private Variables via my()">
and L<"Temporary Values via local()">. To create protected
environments for a set of functions in a separate package (and
probably a separate file), see L<perlmod/"Packages">.
X<formal parameter> X<parameter, formal>
=end original
Perlは名前付き仮引数を持っていません。
C<my()> にこれらのリストを代入することで行えます。
プライベートであると宣言されずに使われている変数は全てグローバル変数です。
プライベート変数に関する詳細はL<"Private Variables via my()"> と
L<"Temporary Values via local()"> を参照してください。
パッケージで(おそらくはファイルでも)分けられている関数のセットのための
保護された環境を作るには L<perlmod/"Packages"> を参照してください。
X<formal parameter> X<parameter, formal>
=begin original
Example:
=end original
例:
sub max {
my $max = shift(@_);
foreach $foo (@_) {
$max = $foo if $max < $foo;
}
return $max;
}
$bestday = max($mon,$tue,$wed,$thu,$fri);
=begin original
Example:
=end original
例:
=begin original
# get a line, combining continuation lines
# that start with whitespace
=end original
# 行を取り、空白で始まる継続行を連結します
sub get_line {
$thisline = $lookahead; # global variables!
LINE: while (defined($lookahead = <STDIN>)) {
if ($lookahead =~ /^[ \t]/) {
$thisline .= $lookahead;
}
else {
last LINE;
}
}
return $thisline;
}
$lookahead = <STDIN>; # get first line
while (defined($line = get_line())) {
...
}
=begin original
Assigning to a list of private variables to name your arguments:
=end original
引数に名前を付けるためにプライベート変数のリストに代入する:
sub maybeset {
my($key, $value) = @_;
$Foo{$key} = $value unless $Foo{$key};
}
=begin original
Because the assignment copies the values, this also has the effect
of turning call-by-reference into call-by-value. Otherwise a
function is free to do in-place modifications of C<@_> and change
its caller's values.
X<call-by-reference> X<call-by-value>
=end original
これは、参照渡しを値渡しにする効果もあります。
なぜなら、値のコピーを代入しているからです。
このようにしないのであれば、関数は自由に C<@_> の値をその場で
書き換えることができ、それはそのまま呼び出し側の値を変更します。
X<call-by-reference> X<call-by-value>
upcase_in($v1, $v2); # this changes $v1 and $v2
sub upcase_in {
for (@_) { tr/a-z/A-Z/ }
}
=begin original
You aren't allowed to modify constants in this way, of course. If an
argument were actually literal and you tried to change it, you'd take a
(presumably fatal) exception. For example, this won't work:
X<call-by-reference> X<call-by-value>
=end original
もちろん、このやり方で定数を変更することは許されません。
ある引数が実際にはリテラルであった場合にその引数を変更しようとすると、
(おそらくは致命的な)例外が引き起こされることになるでしょう。
例えば次の例はうまく働きません。
X<call-by-reference> X<call-by-value>
upcase_in("frederick");
=begin original
It would be much safer if the C<upcase_in()> function
were written to return a copy of its parameters instead
of changing them in place:
=end original
C<upcase_in()> 関数を安全なものにするには、パラメータそのものを
書き換えるのではなくそのコピーを返すように記述するようにします:
($v3, $v4) = upcase($v1, $v2); # this doesn't change $v1 and $v2
sub upcase {
return unless defined wantarray; # void context, do nothing
my @parms = @_;
for (@parms) { tr/a-z/A-Z/ }
return wantarray ? @parms : $parms[0];
}
=begin original
Notice how this (unprototyped) function doesn't care whether it was
passed real scalars or arrays. Perl sees all arguments as one big,
long, flat parameter list in C<@_>. This is one area where
Perl's simple argument-passing style shines. The C<upcase()>
function would work perfectly well without changing the C<upcase()>
definition even if we fed it things like this:
=end original
この(プロトタイプがついていない)関数が自分に対して本当のスカラが
渡されたのか配列が渡されたのかを気にしていないということに注意してください。
Perl は一つの巨大な平坦な(リストの中にリストが含まれることはない、
ということ) C<@_> パラメータリストとして全ての引数を見るのです。
これは Perl の単純な引数渡しの形式のやり方の一つです。
この C<upcase()> 関数は、以下のような呼び出しをした場合でも C<upcase()> の
定義を変更することなく完璧に動作します:
@newlist = upcase(@list1, @list2);
@newlist = upcase( split /:/, $var );
=begin original
Do not, however, be tempted to do this:
=end original
ただし、以下のような呼び出しをやろうとしてはいけません:
(@a, @b) = upcase(@list1, @list2);
=begin original
Like the flattened incoming parameter list, the return list is also
flattened on return. So all you have managed to do here is stored
everything in C<@a> and made C<@b> empty. See
L<Pass by Reference> for alternatives.
=end original
関数に渡される引数リストは平坦なリストであるのと同様、戻り値のリストも
また平坦なリストです。
ですから、関数が返した全ての要素は C<@a> に格納され、C<@b> は
空になります。
別のやり方については L</"Pass by Reference"> を参照してください。
=begin original
A subroutine may be called using an explicit C<&> prefix. The
C<&> is optional in modern Perl, as are parentheses if the
subroutine has been predeclared. The C<&> is I<not> optional
when just naming the subroutine, such as when it's used as
an argument to defined() or undef(). Nor is it optional when you
want to do an indirect subroutine call with a subroutine name or
reference using the C<&$subref()> or C<&{$subref}()> constructs,
although the C<< $subref->() >> notation solves that problem.
See L<perlref> for more about all that.
X<&>
=end original
サブルーチンは、明示的な C<&> というプリフィックスを付けて呼び出すことが
できます。
最近の Perl では C<&> は省略可能であり、サブルーチンがあらかじめ
宣言されている場合には括弧も省略できます。
defined() や undef() の引数として使ったような、単なる名前付き
サブルーチンであるときの C<&> は B<省略可能ではありません>。
C<&$subref()> や C<&{$subref}()> のような、サブルーチンの名前や
リファレンスを使った間接的なサブルーン呼び出しを行いたいたいときにも
C<&> は省略することはできません。
但しC<< $subref->() >> の記法が問題を解決します。
詳しくは L<perlref> を参照してください。
X<&>
=begin original
Subroutines may be called recursively. If a subroutine is called
using the C<&> form, the argument list is optional, and if omitted,
no C<@_> array is set up for the subroutine: the C<@_> array at the
time of the call is visible to subroutine instead. This is an
efficiency mechanism that new users may wish to avoid.
X<recursion>
=end original
サブルーチンは再帰的に呼び出すこともできます。
あるサブルーチンが C<&> 付きで呼び出されたなら、引数リストは省略可能で、
もし省略されたなら、そのサブルーチンに対して C<@_> 配列は設定されません:
代わりに呼び出し時の C<@_> 配列がサブルーチンに対して可視となります。
これは新しいユーザーが避けたいと思う効果的なメカニズムです。
X<recursion>
=begin original
&foo(1,2,3); # pass three arguments
foo(1,2,3); # the same
=end original
&foo(1,2,3); # 三つの引数を渡す
foo(1,2,3); # 上と同じ
=begin original
foo(); # pass a null list
&foo(); # the same
=end original
foo(); # 空リストを渡す
&foo(); # 上と同じ
=begin original
&foo; # foo() get current args, like foo(@_) !!
foo; # like foo() IFF sub foo predeclared, else "foo"
=end original
&foo; # foo() は foo(@_) と同様現在の引数を取る!!
foo; # サブルーチン foo が予め定義されている場合に限り
# foo() と同様、それ以外では "foo"
=begin original
Not only does the C<&> form make the argument list optional, it also
disables any prototype checking on arguments you do provide. This
is partly for historical reasons, and partly for having a convenient way
to cheat if you know what you're doing. See L<Prototypes> below.
X<&>
=end original
C<&> 形式は引数リストを省略可能にするばかりでなく、与えられた引数に
対するすべてのプロトタイプチェックも無効にします。
これは一部には歴史的な理由であり、一部にはあなたが自分の行っている動作を
わかっているときにうまくごまかしを行う便利な方法を残しておくためです。
後に出てくる L<Prototypes> を参照してください。
X<&>
=begin original
Subroutines whose names are in all upper case are reserved to the Perl
core, as are modules whose names are in all lower case. A subroutine in
all capitals is a loosely-held convention meaning it will be called
indirectly by the run-time system itself, usually due to a triggered event.
Subroutines that do special, pre-defined things include C<AUTOLOAD>, C<CLONE>,
C<DESTROY> plus all functions mentioned in L<perltie> and L<PerlIO::via>.
=end original
名前が全て大文字であるサブルーチンは、
名前が全て小文字のモジュール名が (訳注: pragma 用として) 予約されているのと同じように
Perl のコアで予約されています。実行時にシステム自身によって
(通常はイベントをトリガーとして) 間接的に呼び出されるサブルーチンは、
名前を全て大文字で書くのがしきたりです。
特殊で、あらかじめ決められていることをするサブルーチンは、
C<AUTOLOAD>, C<CLONE>, C<DESTROY> に、L<perltie> と L<PerlIO::via> で
説明されている関数全てを加えたものです。
=begin original
The C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT> and C<END> subroutines
are not so much subroutines as named special code blocks, of which you
can have more than one in a package, and which you can B<not> call
explicitly. See L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END">
=end original
The C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT>, C<END> サブルーチンは
サブルーチンというよりは特殊コードブロックで、その中でも一つのパッケージに
複数作ることができ、明示的には B<呼び出せません> 。
L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END"> を参照してください。
=head2 Private Variables via my()
X<my> X<variable, lexical> X<lexical> X<lexical variable> X<scope, lexical>
X<lexical scope> X<attributes, my>
(my() によるプライベート変数)
=begin original
Synopsis:
=end original
概要:
my $foo; # declare $foo lexically local
my (@wid, %get); # declare list of variables local
my $foo = "flurp"; # declare $foo lexical, and init it
my @oof = @bar; # declare @oof lexical, and init it
my $x : Foo = $y; # similar, with an attribute applied
=begin original
B<WARNING>: The use of attribute lists on C<my> declarations is still
evolving. The current semantics and interface are subject to change.
See L<attributes> and L<Attribute::Handlers>.
=end original
B<警告>: C<my> 定義での属性リストの使用はいまだ改良の途中です。
現在の文法とインターフェースは変更される可能性があります。
L<attributes> と L<Attribute::Handlers> を参照してください。
=begin original
The C<my> operator declares the listed variables to be lexically
confined to the enclosing block, conditional (C<if/unless/elsif/else>),
loop (C<for/foreach/while/until/continue>), subroutine, C<eval>,
or C<do/require/use>'d file. If more than one value is listed, the
list must be placed in parentheses. All listed elements must be
legal lvalues. Only alphanumeric identifiers may be lexically
scoped--magical built-ins like C<$/> must currently be C<local>ized
with C<local> instead.
=end original
C<my> 演算子は、それを囲んでいるブロック、条件文 (C<if/unless/elsif/else>)、
ループ(C<for/foreach/while/until/continue>)、サブルーチン、C<eval>、
あるいは C<do/require/use> されたファイルにレキシカルに閉じ込められる
変数を定義します。二つ以上リストアップされている場合には、そのリストは
括弧でくくられていなければなりません。
すべてのリスト要素は正しい左辺値でなければなりません。
C<$/> のような組み込み変数が現時点では C<local> で
B<局所化> されなければならないのに対し、
アルファベットと数字による識別子はレキシカルでマジカルなスコープになります。
=begin original
Unlike dynamic variables created by the C<local> operator, lexical
variables declared with C<my> are totally hidden from the outside
world, including any called subroutines. This is true if it's the
same subroutine called from itself or elsewhere--every call gets
its own copy.
X<local>
=end original
C<local> 文によって生成される動的変数とは異なり、C<my> を使って
宣言されたレキシカル変数はそれを呼び出したサブルーチンも含め、外側の
世界からは秘匿されます。
自分自身が同じサブルーチンを呼んだ場合でさえそうです。
個々の呼び出しはそれぞれのコピーを所有します。
X<local>
=begin original
This doesn't mean that a C<my> variable declared in a statically
enclosing lexical scope would be invisible. Only dynamic scopes
are cut off. For example, the C<bumpx()> function below has access
to the lexical $x variable because both the C<my> and the C<sub>
occurred at the same scope, presumably file scope.
=end original
このことは静的に閉じているレキシカルスコープで宣言されている
C<my> 変数が見えなくなるということは意味しません。
動的変数だけが切り取られます。例を挙げると、以下の C<bumpx()> は
レキシカル変数 $x にアクセスします。
なぜなら、C<my> と C<sub> の両方が同じスコープに現れているからです。
my $x = 10;
sub bumpx { $x++ }
=begin original
An C<eval()>, however, can see lexical variables of the scope it is
being evaluated in, so long as the names aren't hidden by declarations within
the C<eval()> itself. See L<perlref>.
X<eval, scope of>
=end original
しかしながら C<eval()> は、C<eval()> 自身の内側にある宣言によって隠されない
名前の寿命と同じ長さを持つスコープのレキシカル変数を見ることができます。
L<perlref> を参照してください。
X<eval, scope of>
=begin original
The parameter list to my() may be assigned to if desired, which allows you
to initialize your variables. (If no initializer is given for a
particular variable, it is created with the undefined value.) Commonly
this is used to name input parameters to a subroutine. Examples:
=end original
my() に対するパラーメータリストには、お望みとあらば変数を初期化するための
代入を行うことができます(変数に対して初期値が与えられなければ、
その変数は未定義値を使って生成されます)。
一般的にこの機能はサブルーチンに対する入力パラメータに名前を付けるために
使われています。例を挙げましょう:
$arg = "fred"; # "global" variable
$n = cube_root(27);
print "$arg thinks the root is $n\n";
fred thinks the root is 3
sub cube_root {
my $arg = shift; # name doesn't matter
$arg **= 1/3;
return $arg;
}
=begin original
The C<my> is simply a modifier on something you might assign to. So when
you do assign to variables in its argument list, C<my> doesn't
change whether those variables are viewed as a scalar or an array. So
=end original
C<my> は、あなたが代入を行いたいと考えている何かに対する修飾子です。
ですから、引数リストの中にある変数に対して代入を行うときには C<my> は
それらの変数がスカラとして見えているのか配列として見えているかという
状態を変えることはありません。ですから、
my ($foo) = <STDIN>; # WRONG?
my @FOO = <STDIN>;
=begin original
both supply a list context to the right-hand side, while
=end original
これらの両方ともが右辺をリストコンテキストにするのに対して、
my $foo = <STDIN>;
=begin original
supplies a scalar context. But the following declares only one variable:
=end original
これはスカラコンテキストを与えます。しかし、以下のような宣言を
行った場合、一つの変数だけが有効です:
my $foo, $bar = 1; # WRONG
=begin original
That has the same effect as
=end original
これは以下のように書いたのと同じことになります
my $foo;
$bar = 1;
=begin original
The declared variable is not introduced (is not visible) until after
the current statement. Thus,
=end original
宣言された変数は、その文が終了するまでは導入されません(不可視の
状態です)。
したがって、
my $x = $x;
=begin original
can be used to initialize a new $x with the value of the old $x, and
the expression
=end original
これは古い $x の値を使って新しい $x を初期化するのに使うことができます。
そして
my $x = 123 and $x == 123
=begin original
is false unless the old $x happened to have the value C<123>.
=end original
これは古い $x の値がたまたま C<123> でない限り、新しい $x には偽が
設定されます。
=begin original
Lexical scopes of control structures are not bounded precisely by the
braces that delimit their controlled blocks; control expressions are
part of that scope, too. Thus in the loop
=end original
制御構文のレキシカルスコープは、その制御ブロックを区切る中かっこによって
厳格に束縛されることはありません;
制御式もまた、スコープの一部です。
ですから以下のループでは
while (my $line = <>) {
$line = lc $line;
} continue {
print $line;
}
=begin original
the scope of $line extends from its declaration throughout the rest of
the loop construct (including the C<continue> clause), but not beyond
it. Similarly, in the conditional
=end original
$line のスコープはその宣言から(C<continue>ブロックを含む)ループ構造の残りの
部分まで拡張されますが、それを越えることはありません。
同様に、以下の条件文では
if ((my $answer = <STDIN>) =~ /^yes$/i) {
user_agrees();
} elsif ($answer =~ /^no$/i) {
user_disagrees();
} else {
chomp $answer;
die "'$answer' is neither 'yes' nor 'no'";
}
=begin original
the scope of $answer extends from its declaration through the rest
of that conditional, including any C<elsif> and C<else> clauses,
but not beyond it. See L<perlsyn/"Simple Statements"> for information
on the scope of variables in statements with modifiers.
=end original
$answer のスコープはその宣言から条件文の
C<elsif> と C<else> ブロックを含む残りの部分まで拡張されますが、
それを越えることはありません。
修飾子付きの文での変数のスコープに関する情報については
L<perlsyn/"Simple Statements"> を参照してください。
=begin original
The C<foreach> loop defaults to scoping its index variable dynamically
in the manner of C<local>. However, if the index variable is
prefixed with the keyword C<my>, or if there is already a lexical
by that name in scope, then a new lexical is created instead. Thus
in the loop
X<foreach> X<for>
=end original
C<foreach> はその添え字変数に対するスコープをデフォルトでは
C<local> のやり方で動的なものにしています。
しかしながら、添え字変数に C<my> というキーワードが前置されていた場合、
または現在のスコープでその名前がすでにレキシカルである場合には、
新しいレキシカル変数が代わりに作られます。
ですから以下のループでは:
X<foreach> X<for>
for my $i (1, 2, 3) {
some_function();
}
=begin original
the scope of $i extends to the end of the loop, but not beyond it,
rendering the value of $i inaccessible within C<some_function()>.
X<foreach> X<for>
=end original
$i のスコープはループの終端まで拡張されますが、それを越えることはないので、
$i の値は C<some_function()> の中では参照することができなくなります。
X<foreach> X<for>
=begin original
Some users may wish to encourage the use of lexically scoped variables.
As an aid to catching implicit uses to package variables,
which are always global, if you say
=end original
ユーザーの一部には、レキシカルなスコープの変数の使用を奨励することを
望んでいる人もいるでしょう。
常にグローバルであるパッケージ変数に対する暗黙の使用を捕捉することを
助けるものとして、
use strict 'vars';
=begin original
then any variable mentioned from there to the end of the enclosing
block must either refer to a lexical variable, be predeclared via
C<our> or C<use vars>, or else must be fully qualified with the package name.
A compilation error results otherwise. An inner block may countermand
this with C<no strict 'vars'>.
=end original
のようにすると、この文からそれを囲むブロックの終端までの間の変数の参照は、
レキシカル変数に対する参照か、C<our> または C<use vars> による
事前宣言か、さもなければ完全なパッケージ名で修飾した
名前でなければなりません。
それ以外のものがあるとコンパイルエラーが発生します。
これの対象となっているブロックの内側にあるブロックで
C<no strict 'vars'> とすると(内側のブロック中では)この制限を
取り消すことができます。
=begin original
A C<my> has both a compile-time and a run-time effect. At compile
time, the compiler takes notice of it. The principal usefulness
of this is to quiet C<use strict 'vars'>, but it is also essential
for generation of closures as detailed in L<perlref>. Actual
initialization is delayed until run time, though, so it gets executed
at the appropriate time, such as each time through a loop, for
example.
=end original
C<my> はコンパイル時の効果と実行時の効果の両方を持っています。
コンパイル時においては、コンパイラはその変数を認識します。
これの基本的な実用性は C<use strict 'vars'> を黙らせるということですが、
L<perlref> で詳細を記述しているクロージャの作成にも有用です。
実際の初期化は実行時まで遅らされ、そのためたとえばループを通る度に
適切に実行されるのです。
=begin original
Variables declared with C<my> are not part of any package and are therefore
never fully qualified with the package name. In particular, you're not
allowed to try to make a package variable (or other global) lexical:
=end original
C<my> によって宣言された変数はどのパッケージの一部でもなく、
そのためパッケージ名を使って修飾されることは決してありません。
特に、パッケージ変数(もしくはその他のグローバルな変数)を
レキシカルにしようとすることは許されていません。
my $pack::var; # ERROR! Illegal syntax
=begin original
In fact, a dynamic variable (also known as package or global variables)
are still accessible using the fully qualified C<::> notation even while a
lexical of the same name is also visible:
=end original
実際のところ、動的変数(パッケージ変数やグローバル変数として
知られているもの)は、同じ名前を持ったレキシカルが可視な状態であったとしても、
C<::> 記法を使った(名前の)完全な修飾を行うことによって
まだアクセス可能なのです:
package main;
local $x = 10;
my $x = 20;
print "$x and $::x\n";
=begin original
That will print out C<20> and C<10>.
=end original
この例は C<20> と C<10> を出力します。
=begin original
You may declare C<my> variables at the outermost scope of a file
to hide any such identifiers from the world outside that file. This
is similar in spirit to C's static variables when they are used at
the file level. To do this with a subroutine requires the use of
a closure (an anonymous function that accesses enclosing lexicals).
If you want to create a private subroutine that cannot be called
from outside that block, it can declare a lexical variable containing
an anonymous sub reference:
=end original
このファイルの外側の世界からこのような識別子を隠すために、C<my> 変数を
ファイルの最も外側のスコープで宣言することができます。
これは、概念としては C でのファイルレベルの static 変数と似ています。
これをサブルーチンの内側で行うには、
クロージャ(レキシカルアクセスを伴った無名関数)を使います。
ブロックで外側のブロックから呼び出すことのできないようなプライベートな
サブルーチンを作りたいなら、無名サブルーチンのリファレンスを
保持するレキシカル変数を宣言することができます:
my $secret_version = '1.001-beta';
my $secret_sub = sub { print $secret_version };
&$secret_sub();
=begin original
As long as the reference is never returned by any function within the
module, no outside module can see the subroutine, because its name is not in
any package's symbol table. Remember that it's not I<REALLY> called
C<$some_pack::secret_version> or anything; it's just $secret_version,
unqualified and unqualifiable.
=end original
このリファレンスが決して、モジュールの内側にあるどんな関数からも
返されることがないのと同様に、外側のモジュールはサブルーチンを
見ることができません。
なぜなら、その名前はどのパッケージのシンボルテーブルにも
存在していないからです。
C<$some_pack::secret_version> などの手段を使って呼び出すことは
B<できない> のだということを思い出してください。
これは単なる $secret_version であって、修飾されることはなく
修飾することはできません。
=begin original
This does not work with object methods, however; all object methods
have to be in the symbol table of some package to be found. See
L<perlref/"Function Templates"> for something of a work-around to
this.
=end original