3 package String::RewritePrefix;
6 use Sub::Exporter -setup => {
7 exports => [ rewrite => \'_new_rewriter' ],
12 String::RewritePrefix - rewrite strings based on a set of known prefixes
20 use String::RewritePrefix;
21 my @to_load = String::RewritePrefix->rewrite(
22 { '' => 'MyApp::', '+' => '' },
23 qw(Plugin Mixin Addon +Corporate::Thinger),
27 qw(MyApp::Plugin MyApp::Mixin MyApp::Addon Corporate::Thinger)
29 You can also import a rewrite routine:
31 use String::RewritePrefix rewrite => {
32 -as => 'rewrite_dt_prefix',
33 prefixes => { '' => 'MyApp::', '+' => '' },
36 my @to_load = rewrite_dt_prefix( qw(Plugin Mixin Addon +Corporate::Thinger));
39 qw(MyApp::Plugin MyApp::Mixin MyApp::Addon Corporate::Thinger)
43 our $VERSION = '0.005';
49 String::RewritePrefix->rewrite(\%prefix, @strings);
51 This rewrites all the given strings using the rules in C<%prefix>. Its keys
52 are known prefixes for which its values will be substituted. This is performed
53 in longest-first order, and only one prefix will be rewritten.
55 If the prefix value is a coderef, it will be executed with the remaining string
56 as its only argument. The return value will be used as the prefix.
61 my ($self, $arg, @rest) = @_;
62 return $self->_new_rewriter(rewrite => { prefixes => $arg })->(@rest);
66 my ($self, $name, $arg) = @_;
67 my $rewrites = $arg->{prefixes} || {};
70 for my $prefix (sort { length $b <=> length $a } keys %$rewrites) {
71 push @rewrites, ($prefix, $rewrites->{$prefix});
77 Carp::cluck("string rewriter invoked in void context")
78 unless defined wantarray;
80 Carp::croak("attempt to rewrite multiple strings outside of list context")
81 if @_ > 1 and ! wantarray;
83 STRING: for my $str (@_) {
84 for (my $i = 0; $i < @rewrites; $i += 2) {
85 if (index($str, $rewrites[$i]) == 0) {
86 if (ref $rewrites[$i+1]) {
87 my $rest = substr $str, length($rewrites[$i]);
88 push @result, $rewrites[$i+1]->($rest) . $rest;
90 push @result, $rewrites[$i+1] . substr $str, length($rewrites[$i]);
99 return wantarray ? @result : $result[0];
105 Ricardo SIGNES <rjbs@cpan.org>
107 =head1 COPYRIGHT AND LICENSE
109 This software is copyright (c) 2008 by Ricardo SIGNES.
111 This is free software; you can redistribute it and/or modify it under
112 the same terms as perl itself.