在有或没有删除的情况下清除受祝福的哈希成员

Untainting a blessed hash member with or without the delete

我在一些资源中看到了这行代码

( $self->{arg} ) = ( ( delete $self->{arg} ) =~ /(.*)/s ) if ${^TAINT}; 

我理解去污染。我也知道delete

我的问题是,在什么情况下有必要或更愿意使用delete,而使用更简单的

还不够吗?
( $self->{arg} ) = ( ( $self->{arg} ) =~ /(.*)/s ) if ${^TAINT};

例如

#!/usr/bin/env perl -T

use 5.014;
use warnings;

package Some {
    use Moose;
    has 'arg' => (is => 'rw', isa => 'Str');
    sub doit {
        my $self = shift;
        #( $self->{arg} ) = ( ( delete $self->{arg} ) =~ /(.*)/s ) if ${^TAINT};
        ( $self->{arg} ) = ( ( $self->{arg} ) =~ /(.*)/s ) if ${^TAINT};
    }
};

my $some = Some->new( arg => 'some text' );
$some->doit();
say $some->arg;

使用普通散列删除值并重新插入将产生与就地修改相同的结果。

commit does not give any information about why he deletes it just that he copies the functionality from Mason 1. But if you look at the source of HTML::Mason::Lexer,你会发现这条评论:

We need to untaint the component or else the regexes will fail to a Perl bug. The delete is important because we need to create an entirely new scalar, not just modify the existing one.

($current->{comp_source}) = (delete $current->{comp_source}) =~ /(.*)/s if taint_is_on;

所以这样做的原因是为了有一个新的标量,尽管他没有为他正在清除的其他地方这样做:Mason::Interp,所以我猜是一个更早的 Perl 错误,去污染时。

所以区别在于 delete 会给你一个新的标量,尽管这很少有实际应用。 (删除和插入当然也是比较慢的操作。)

use strict;
my $hash->{test} = 'test';
print \($hash->{test}),"\n";
( $hash->{test} ) = ( ( $hash->{test} ) =~ /(.*)/s );
print \($hash->{test}),"\n";
( $hash->{test} ) = ( ( delete $hash->{test} ) =~ /(.*)/s );
print \($hash->{test}),"\n";

给予

SCALAR(0x7f84d10047e8)
SCALAR(0x7f84d10047e8)
SCALAR(0x7f84d1029230)