LoginSignup
1
0

More than 5 years have passed since last update.

state演算子(静的変数)が使えない環境での代替方法

Posted at

静的変数、C言語でいうところのstatic変数というものがある。

静的変数とは|スタティック変数|static変数|static variable - 意味/定義 : IT用語辞典

関数で2度目の呼び出しが行われた時、前回の値を引き継ぐちょっと変わった変数で、
これを使うと外部からアクセスできないprivateな変数にしたり、前回の結果をキャッシュしたりすることができる。
Perlでは5.10から導入されたため、それ以前の環境下では使えないが、
クロージャという仕組みを使うと同等のことが可能になる。

cache.pl
#!/usr/bin/perl

use strict;
use warnings;

my @hoge = get_filelist();
print "hoge end $#hoge\n";
my @foo = get_filelist();
print "foo end $#foo\n";

{
        my @list;
        sub get_filelist {
                if (0 == scalar @list) {
                        @list = `find /etc`;
                }
                else {
                        print "cashed\n";
                }
                return @list;
        }
}

上記はfindの結果を@listにキャッシュしておき、2度目の呼び出し時は
その結果を返すサンプルである。"cached"が標準出力されており、キャッシュを返している様子がわかる。

$ perl cache.pl
hoge end 1226
cashed
foo end 1226

なお、@listは外側でアクセスできないので仮に呼び出してもコンパイルエラーになり、隠蔽されていることが確認できる。

$ perl -c cashe.pl
Possible unintended interpolation of @list in string at a.pl line 25.
Global symbol "@list" requires explicit package name at a.pl line 25.
Execution of a.pl aborted due to compilation errors.

参考

Perl クロージャによる永続的なプライベート変数 closure, state (0x26c)|Perl Perl_5|blog20100901
http://pointoht.ti-da.net/e8120632.html

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0