什么是“字符串化"?在 Perl 中? [英] What is "stringification" in Perl?
问题描述
在 CPAN 模块的文档中 DateTime 我发现了以下内容:
In the documentation for the CPAN module DateTime I found the following:
一旦你设置了格式化程序,重载的字符串化方法将使用格式化程序.
Once you set the formatter, the overloaded stringification method will use the formatter.
似乎有一些 Perl 概念被称为字符串化",但我不知为何错过了.谷歌搜索并没有对此进行太多澄清.这是什么字符串化"?
It seems there is some Perl concept called "stringification" that I somehow missed. Googling has not clarified it much. What is this "stringification"?
推荐答案
"stringification" 发生在 perl 需要将值转换为字符串的任何时候.这可能是打印它,将它与另一个字符串连接起来,对其应用正则表达式,或者使用 Perl 中的任何其他字符串操作函数.
"stringification" happens any time that perl needs to convert a value into a string. This could be to print it, to concatenate it with another string, to apply a regex to it, or to use any of the other string manipulation functions in 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 打印它被祝福到的包,以及引用的类型和地址.
Normally, objects will stringify to something like Some::Package=HASH(0x467fbc)
where perl is printing the package it is blessed into, and the type and address of the reference.
某些模块选择覆盖此行为.在 Perl 中,这是通过 overload 编译指示完成的.下面是一个对象的例子,当字符串化时产生它的总和:
Some modules choose to override this behavior. In Perl, this is done with the overload pragma. Here is an example of an object that when stringified produces its sum:
{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'
overload
还允许您定义其他几种定义:
There are several other ifications that overload
lets you define:
'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/)`
对象甚至可以表现为不同的类型:
Objects can even behave as different types:
'${}' 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;`
这篇关于什么是“字符串化"?在 Perl 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!