加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

在Perl中是否有方便安全解除引用?

发布时间:2020-12-15 21:45:36 所属栏目:大数据 来源:网络整理
导读:所以perl5porters正在讨论添加一个安全的解除引用运算符,以允许类似的东西 $ceo_car_color = $company-ceo-car-color if defined $company and defined $company-ceo and defined $company-ceo-car; 被缩短为例如 $ceo_car_color = $company-ceo-car-color;
所以perl5porters正在讨论添加一个安全的解除引用运算符,以允许类似的东西
$ceo_car_color = $company->ceo->car->color
    if  defined $company
    and defined $company->ceo
    and defined $company->ceo->car;

被缩短为例如

$ceo_car_color = $company->>ceo->>car->>color;

其中$foo->> bar意味着定义$foo? $foo-> bar:undef.

问题是:是否有一些模块或不引人注目的黑客攻击我,这个操作符,或类似的行为,具有视觉上令人愉快的语法?

为了您的乐趣,我会列出我能够提出的想法.

>多重derefencing方法(看起来很丑).

sub multicall {
    my $instance = shift // return undef;
    for my $method (@_) {
        $instance = $instance->$method() // return undef;
    }
    return $instance;
}

$ceo_car_color = multicall($company,qw(ceo car color));

>一个包装器,它将undef变成一个代理对象(看起来更丑陋),它从所有函数调用中返回undef.

{ package Safe; sub AUTOLOAD { return undef } }
sub safe { (shift) // bless {},'Safe' }

$ceo_car_color = safe(safe(safe($company)->ceo)->car)->color;

>因为我可以访问ceo(),car()和color()的实现,所以我想过直接从这些方法返回安全代理,但是现有代码可能会破坏:

my $ceo = $company->ceo;
my $car = $ceo->car if defined $ceo; # defined() breaks

不幸的是,在perldoc重载中没有看到任何关于在我的安全代理中重载了定义和//的含义的内容.

解决方法

也许这不是最有用的解决方案,但它是一个WTDI(nr.1的变体),它是一个非常简单的用例,用于 List::Util的减少,这是非常罕见的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读