【发布时间】:2010-04-08 18:02:50
【问题描述】:
我遇到了一种情况(在记录各种数据更改时),我需要确定引用是否具有有效的字符串强制转换(例如,可以正确地打印到日志中或存储在数据库中)。 Scalar::Util 中没有任何东西可以做到这一点,所以我使用该库中的其他方法拼凑了一些东西:
use strict;
use warnings;
use Scalar::Util qw(reftype refaddr);
sub has_string_coercion
{
my $value = shift;
my $as_string = "$value";
my $ref = ref $value;
my $reftype = reftype $value;
my $refaddr = sprintf "0x%x", refaddr $value;
if ($ref eq $reftype)
{
# base-type references stringify as REF(0xADDR)
return $as_string !~ /^${ref}\(${refaddr}\)$/;
}
else
{
# blessed objects stringify as REF=REFTYPE(0xADDR)
return $as_string !~ /^${ref}=${reftype}\(${refaddr}\)$/;
}
}
# Example:
use DateTime;
my $ref1 = DateTime->now;
my $ref2 = \'foo';
print "DateTime has coercion: " . has_string_coercion($ref1) . "\n\n";
print "scalar ref has coercion: " . has_string_coercion($ref2) . "\n";
但是,我怀疑通过以某种方式检查变量的内脏可能有更好的方法来确定这一点。怎样才能做得更好?
【问题讨论】: