sub search_me { my $self = shift; my ($search) = @_; my @results = (); foreach my $attr ( qw/title message author/ ) { if ( $self->$attr() =~ m/$search/ ) { push(@results, { 'name' => $attr, 'value' => $self->$attr() }); } } return @results; } #### $VAR1 = [ { 'name' => 'title', 'value' => 'My title xyzzy' } ]; #### package Note::Attribute::Trait::Searchable { use Moose::Role; Moose::Util::meta_attribute_alias('Searchable'); } #### package Note::Searchable { use Moose::Role; sub search { my $self = shift; my ($search_string) = @_; my $meta = $self->meta; my @results; # Go through all attributes on your object foreach my $attribute ( map { $meta->get_attribute($_) } sort $meta->get_attribute_list ) { # Skip attributes unless they're specifically searchable unless ( $attribute->does('Note::Attribute::Trait::Searchable') ) { next; } my $reader = $attribute->get_read_method(); my $value = $self->$reader; if ( $value =~ m/$search_string/ ) { push( @results, { 'name' => $attribute->name, 'value' => $value } ); } } return @results; } } #### package Note { use Moose; with 'Note::Searchable'; # We want to search title, message, and author has 'title' => ( is => 'rw', isa => 'Str', traits => [qw/Searchable/] ); has 'message' => ( is => 'rw', isa => 'Str', traits => [qw/Searchable/] ); has 'author' => ( is => 'rw', isa => 'Str', traits => [qw/Searchable/] ); # We don't want to search "other" has 'other' => ( is => 'rw', isa => 'Str' ); no Moose; } #### my $note = Note->new( title => 'My title xyzzy', message => 'My message', author => 'me' ); use Data::Dumper; say Dumper [ $note->search('xyzzy') ]; #### $VAR1 = [ { 'name' => 'title', 'value' => 'My title xyzzy' } ];