にぽたん研修所 兼 にぽたん休憩所

旧にぽたん休憩所をマージしたからわけがわからない

overload のやつ

http://naoya.g.hatena.ne.jp/naoya/20060703/1151907779

これの結果が、ほんとは

hello
My::String
world
My::String

となって欲しいんだけど、

hello
My::String
world

となって置換後の $str が My::String じゃなくなってしまうという。

これは、このことじゃないのかな。
perldoc overload より。

Losing overloading
       The restriction for the comparison operation is that even if, for exam-
       ple, `"cmp"' should return a blessed reference, the autogenerated
       `"lt"' function will produce only a standard logical value based on the
       numerical value of the result of `"cmp"'.  In particular, a working
       numeric conversion is needed in this case (possibly expressed in terms
       of other conversions).

       Similarly, ".="  and "x=" operators lose their mathemagical properties
       if the string conversion substitution is applied.

       When you chop() a mathemagical object it is promoted to a string and
       its mathemagical properties are lost.  The same can happen with other
       operations as well.


置換とか chop() とかは、mathemagical (mathematical?) 特性を失うとかそういう話。

#!/usr/local/bin/perl
use strict;
use warnings;

my $str = My::String->new('hello');
print $str, "\n";
print ref $str, "\n";

#$str =~ s/hello/world/g;
$str .= ' world';
print $str, "\n";
print ref $str, "\n";

chop $str;
print $str, "\n";
print ref $str, "\n";


package My::String;
use strict;
use warnings;
use overload q{""} => sub { shift->stringify },
             q{.=} => \&append_string;

sub new {
    bless { string => $_[1] }, $_[0];
}

sub stringify {
    shift->{string};
}

sub append_string {
    my $self = shift;
    $self->{string} .= shift;
    return $self;
}

1;

こんなんすると

hello
My::String
hello world
My::String
hello worl

chop() 実行したらリファレンスが失われた。
chomp() も置換もあかんかった。


こういうことではないのかな。
実はいまひとつわかってないで書いてますが。