链接一个变量Perl中的类属性 [英] Link a variable to a class attribute in Perl

查看:145
本文介绍了链接一个变量Perl中的类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题诞生出另一个(<一个href=\"http://stackoverflow.com/questions/31841484/completely-destroy-all-traces-of-an-object-in-perl/31841647#comment51614865_31841647\">Completely消灭在Perl 对象的所有痕迹)。看到了一些我相信我已经到了真正的问题缩小了问题的意见后。

This question was born out of another (Completely destroy all traces of an object in Perl). After seeing some of the comments I believe I have narrowed the problem down to the "real" issue.

我在寻找一个简单的方法给一个变量链接到Perl中的类属性,这样每当属性被修改,该变量将自动更新。

I'm looking for a simple way to link a variable to a class attribute in Perl so that whenever the attribute is modified, the variable will be automatically updated.

EX(一些伪code):

ex (some pseudo code):

# Create a file object
my $file = File->new();

# Get the text
my $text = $file->text();

# prints 'hello'
print $text;

# Set the text
$file->text('goodbye');

# prints 'goodbye'
print $text;

此外,我想读的 $文本变量只有这样你可以不小心修改文本属性该文件。

Also I want the $text variable to be read only so that you cannot inadvertently modify the text attribute of the file.

推荐答案

使用领带

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

{   package File;

    sub new {
        bless ['hello'], shift
    }

    sub text {
        my $self = shift;
        if (@_) {
            $self->[0] = shift;
        } else {
            return $self->[0]
        }
    }
}

{   package FileVar;
    use Tie::Scalar;
    use parent qw( -norequire Tie::StdScalar );

    sub TIESCALAR {
        my ($class, $obj) = @_;
        bless \$obj, $class
    }

    sub FETCH {
        my $self = shift;
        ${$self}->text()
    }

    sub STORE {
        die 'Read only!';

        # Or, do you want to change the object by changing the var, too?
        my ($self, $value) = @_;
        ${$self}->text($value);
    }

}

my $file = 'File'->new();
tie my $text, 'FileVar', $file;
say $text;
$file->text('goodbye');
say $text;

# Die or change the object:
$text = 'Magic!';
say $file->text;

这篇关于链接一个变量Perl中的类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆