在CPAN模块
DateTime的文档中,我发现以下内容:
Once you set the formatter,the
overloaded stringification method will
use the formatter.
似乎有一些Perl概念叫做“伪装”,我以某种方式错过了。谷歌还没有澄清。这是什么?
解决方法
perl需要将值转换为字符串时,“stringification”会发生。这可能是打印它,将其连接到另一个字符串,以将正则表达式应用于它,或使用Perl中的其他任何字符串操作函数。
say $obj; say "object is: $obj"; if ($obj =~ /xyz/) {...} say join ',' => $obj,$obj2,$obj3; if (length $obj > 10) {...} $hash{$obj}++; ...
通常,对象将会像Some :: Package = HASH(0x467fbc)这样的字符串,其中perl正在打印它所包含的包,以及引用的类型和地址。
某些模块选择覆盖此行为。在Perl中,这是用overload的pragma来完成的。下面是一个对象的示例:当stringified生成其总和时:
{package Sum; use List::Util (); sub new {my $class = shift; bless [@_] => $class} use overload fallback => 1,'""' => sub {List::Util::sum @{$_[0]}}; sub add {push @{$_[0]},@_[1 .. $#_]} } my $sum = Sum->new(1 .. 10); say ref $sum; # prints 'Sum' say $sum; # prints '55' $sum->add(100,1000); say $sum; # prints '1155'
还有几个其他的说明,重载可以让你定义:
'bool' Boolification The value in boolean context `if ($obj) {...}` '""' Stringification The value in string context `say $obj; length $obj` '0+' Numification The value in numeric context `say $obj + 1;` 'qr' Regexification The value when used as a regex `if ($str =~ /$obj/)`
对象甚至可以表现为不同的类型:
'${}' Scalarification The value as a scalar ref `say $$obj` '@{}' Arrayification The value as an array ref `say for @$obj;` '%{}' Hashification The value as a hash ref `say for keys %$obj;` '&{}' Codeification The value as a code ref `say $obj->(1,2,3);` '*{}' Globification The value as a glob ref `say *$obj;`