home ホーム search 検索 -  login ログイン  | reload edit datainfo version cmd icon diff delete  | help ヘルプ

Perl/codepiece/static_vars1

Perl/codepiece/static_vars1

Perl / codepiece / static_vars1
id: 111 所有者: msakamoto-sf    作成日: 2007-02-25 22:09:00
カテゴリ: Perl 

  • Perlには、C/PHP にあるようなstatic変数(関数内部の局所変数で、かつ、関数を抜けた後も値が保持される性質の変数)は存在しない。
  • しかし、lexical変数は"{}"内のスコープを持っている為、これを利用して疑似static変数を使用できる。
  • Perl >= 5.0?
  • コードピース
#!/usr/bin/perl
#use strict; <<<< 末尾のprintを使用しなければ有効化して大丈夫。
package test;
{
	my $count;
	sub countup { $count++; $count; }
}
package main;
print &test::countup(), "\n";
print &test::countup(), "\n";
print &test::countup(), "\n";
print &test::countup(), "\n";

print '$count is not defined', "\n" if !defined($count);
print '$test::count is not defined', "\n" if !defined($test::count);
  • 出力
1
2
3
4
$count is not defined
$test::count is not defined

只の"{}"でsubを囲む。lexical変数の場合、本当の意味で"機械的に"スコーピングしてくれる為、只の"{}"といえど、その中のmyはその中で保持される。これにより、"staticに見える"状況を創り出している。



プレーンテキスト形式でダウンロード
現在のバージョン : 1
更新者: msakamoto-sf
更新日: 2008-12-24 22:11:19
md5:61eb9a0548ff64d43983cd45ad3347b2
sha1:8fca48ec5cecc5822b584fcb3ec6d69569fe145f
コメント
コメントを投稿するにはログインして下さい。