camel

素敵!

演算子 | を overload して TT のフィルタみたいな記法を実装する - 酒日記 はてな支店
<?= $value | replace('x','y') | uri ?>
こんな風に書けたら素敵ですよね。ということでこんなのを書いてみた。

でも、そのままではちょっと使いづらいので、その辺を直してSub::PipeとしてCodeReposにうpしておきました。

問題点は、以下の通り。

  • さすがにFilterというモジュール名はまずい。ソースフィルター系とかぶる。
  • 直にcoderefをblessするのはちょっと傲慢さが足りない。

以上を直したのが、以下です。コード部分をAS ISで。

package Sub::Pipe;
use warnings;
use strict;
our $VERSION = '0.01';
use base 'Exporter';
our @EXPORT = qw/joint/;

use overload '|' => sub { $_[0]->( $_[1] ) };

sub joint(&) { bless $_[0], __PACKAGE__ };

if ( $0 eq __FILE__ ) {
    local $\ = "\n";
    my $uri = joint { use URI::Escape; uri_escape_utf8(shift) };
    my $html = joint {
        my $str = shift;
        $str =~ s{([&<>"])}{
            '&' . { qw/& amp  < lt > gt " quot/ }->{$1} . ';' ;
        }msgex;
        $str;
    };
    my $html_line_break = joint {
        local $_ = $_[0];
        s{\r*\n}{<br/>}g;
        $_;
    };
    my $replace = sub {
        my ( $regexp, $replace ) = @_;
        joint {
            my $str = shift;
            $str =~ s{$regexp}{$replace}g;
            $str;
        }
    };
    print "dankogai" | joint { uc shift };
    print "<pre>" | $html;
    print "Perl & Me" | $uri;
    print "PHP" | $replace->( 'HP', 'erl' );
    print "Rock\nRoll" | $html_line_break | $uri;
}

1; # End of Sub::Pipe                                                           

まだCPANにはうpしてません。そのまま id:sfujiwara さんに CodeRepos 経由の寄贈ということで。めんどいならCPANへのうpも私がやっておきますが。

Dan the Perl Monger