| 1 | package Template::Flute::Filter::Replace; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use base 'Template::Flute::Filter'; | ||
| 7 | |||
| 8 | =head1 NAME | ||
| 9 | |||
| 10 | Template::Flute::Filter::Replace - Substitutes literal text in a string. | ||
| 11 | |||
| 12 | =head1 SYNOPSIS | ||
| 13 | |||
| 14 | $replace_filter = Template::Flute::Filter::Replace->new(options => { | ||
| 15 | from => 'foo', | ||
| 16 | to => 'bar', | ||
| 17 | }); | ||
| 18 | |||
| 19 | $barbar = $replace->filter('foobar'); | ||
| 20 | |||
| 21 | =head1 DESCRIPTION | ||
| 22 | |||
| 23 | The replace filter locates a substring within a string and substitutes | ||
| 24 | each occurrence with another string. | ||
| 25 | |||
| 26 | =head1 METHODS | ||
| 27 | |||
| 28 | =head2 init | ||
| 29 | |||
| 30 | Initializes object with replace options. | ||
| 31 | |||
| 32 | =cut | ||
| 33 | |||
| 34 | sub init { | ||
| 35 | my ($self, %args) = @_; | ||
| 36 | |||
| 37 | for (qw/from to/) { | ||
| 38 | $self->{$_} = $args{options}->{$_}; | ||
| 39 | } | ||
| 40 | } | ||
| 41 | |||
| 42 | =head2 filter | ||
| 43 | |||
| 44 | Carries out the actual substitution and returns | ||
| 45 | the filtered value. | ||
| 46 | |||
| 47 | =cut | ||
| 48 | |||
| 49 | sub filter { | ||
| 50 | my ($self, $value) = @_; | ||
| 51 | my ($qtd); | ||
| 52 | |||
| 53 | return $value unless defined $self->{from} | ||
| 54 | && length $self->{from}; | ||
| 55 | |||
| 56 | $qtd = quotemeta($self->{from}); | ||
| 57 | |||
| 58 | $value =~ s/$qtd/$self->{to}/g; | ||
| 59 | |||
| 60 | return $value; | ||
| 61 | } | ||
| 62 | |||
| 63 | =head1 AUTHOR | ||
| 64 | |||
| 65 | Stefan Hornburg (Racke), <racke@linuxia.de> | ||
| 66 | |||
| 67 | =head1 LICENSE AND COPYRIGHT | ||
| 68 | |||
| 69 | Copyright 2012-2019 Stefan Hornburg (Racke) <racke@linuxia.de>. | ||
| 70 | |||
| 71 | This program is free software; you can redistribute it and/or modify it | ||
| 72 | under the terms of either: the GNU General Public License as published | ||
| 73 | by the Free Software Foundation; or the Artistic License. | ||
| 74 | |||
| 75 | See http://dev.perl.org/licenses/ for more information. | ||
| 76 | |||
| 77 | =cut | ||
| 78 | |||
| 79 | 1; |