0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

($a == 1 && $a == 2 && $a == 3) を常に真にできますか?

0
Posted at

(a == 1 && a == 2 && a == 3) を常に真にできますか? その3($a == 1 && $a == 2 && $a == 3) を見て常に真にできますか? その3 に空目して tie だろうな、と思ったら違っていたので tie の思い出しも含めて書いてみた。

コードはこちら。
追加したのは、 package AAA の部分と tie $a, 'AAA'; の部分です。

use strict;
use warnings;

tie $a, 'AAA';
print "True!" if ($a == 1 and $a == 2 and $a == 3);


package AAA;
use strict;
use warnings;
require Tie::Scalar;
my @ISA = qw(Tie::Scalar);

sub TIESCALAR {
    my $class = shift;
    my $instance = @_ ? shift : undef;
    return bless \$instance => $class;
}

sub FETCH {
    ${$_[0]}++;      # 読みだし時に ++ する
    return ${$_[0]};
}

sub STORE {
    ${$_[0]} = $_[1];
}

sub DESTROY {
    undef ${$_[0]};
}

結果は True! と表示されます。

tie とは何か?

以下にはオブジェクトクラスを単純な変数に隠す方法とあります。
上の例では、 FETCH (読み込み) 時に追加の処理を設定しました。
読み込み時に常にディスクから再読み込みするとかそういう用途に使うことができます。

詳しくは以下を読むと良いと思います。

https://perldoc.jp/docs/perl/5.26.1/perltie.pod
https://metacpan.org/pod/perltie

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?