今だから分かるlocal
最近になって$/とか、$\を知って、localを使う機会に恵まれたので、
少しだけlocalを理解できた気がします。
$/とか、$\については、こちらをどうぞ。
Perl で定義済みの変数(perldoc.jp)
例えば、printを実行した時の挙動を変えてみます。
use v5.10;
use strict;
use warnings;
sub foo {
$\ = "\n";
print '$\ has changed!!';
}
print 'a';
print 'b';
print 'c';
print "\n", '----------------', "\n";
foo();
print 'a';
print 'b';
print 'c';
実行すると???
$ perl aaa.pl
abc
----------------
$\ has changed!!
a
b
c
でも、6行目にlocalを付けると・・・。
$ perl bbb.pl
abc
----------------
$\ has changed!!
abc
こんな感じで、挙動を変更する範囲をコントロールできます。
これ、useしてるモジュールにも影響でるのかな???
package Foo {
use strict;
use warnings;
sub foo {
print 'This package is ', __PACKAGE__;
}
}
use strict;
use warnings;
print 'Here is ', __PACKAGE__;
Foo::foo();
print "\n", '------------------', "\n";
$\ = "\n";
print 'Here is ', __PACKAGE__;
Foo::foo();
これを実行すると?
$ perl ccc.pl
Here is mainThis package is Foo
------------------
Here is main
This package is Foo
やっぱ、よろしくないですね。
おしまい。
Leave a Comment