I need to filter the “string” passed to the attribute “query”
and create a url with the filtered value.
my code
package Search;
use Any::Moose;
has query => qw{ is ro isa Str required 1 };
# my method modifiers
around 'query' => sub {
my $orig = shift;
my $self = shift;
my $content = $self->$orig(@_);
# simple filter
$content =~ s{[^\w\-\s]}{}gi;
return $content;
};
sub create_uri {
my $self = shift;
my $uri = "http://localhost/search/".$self->{query};
return $uri;
};
1;
package main;
my $obj = Search->new({
query => 'foo@#$%#%#@&-**bar@@#%!',
});
print $obj->query."\n";
print $obj->create_uri."\n"; # BAD
output here :
print $search->query;
foo-bar , as expected.
When I call “create_uri”
print $search->create_uri;
output :
http://localhost/search/foo@#$%#%#@&-**bar@@#%!
The “query” is completely dirty!
How to solve this?
When you call
print $obj->queryyou are calling the /subroutine/ called query, which calls youraroundsub. When you call$self->{query}from withincreate_uriyou access the /attribute/ called query. There are two solutions:1) Replace
$self->{query}with$self->query2) Instead of using
around query, use thetriggeroption on the attribute, which calls a function every time the attribute is set. See http://metacpan.org/pod/Moose for information.