Search code examples
perloopattributesfiltermoose

method modifiers with moose perl


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?


Solution

  • When you call print $obj->query you are calling the /subroutine/ called query, which calls your around sub. When you call $self->{query} from within create_uri you access the /attribute/ called query. There are two solutions:

    1) Replace $self->{query} with $self->query

    2) Instead of using around query, use the trigger option on the attribute, which calls a function every time the attribute is set. See http://metacpan.org/pod/Moose for information.