How to effectively apply regex replacement by Moose attribute?

I have

package Test;
use Moose;
has 'attr' => ( is => 'rw', isa => 'Str' );

Inside the method, I would like to apply the attribute s/pattern/string/gto the attribute. For the reasons registered with Moose (mainly to properly support polymorphism), I don’t want to contact directly $self->{attr}, so it’s just:

$self->{attr} =~ s/pattern/string/g;

not an option. How can I do this efficiently in speed and small but understandable code with Moose?

Parameters I came up with:

1) Use a temporary variable and the usual getter / setter method:

my $dummy = $self->attr;
$dummy =~ s/pattern/string/g;
$self->attr($dummy);

2) Using attr getter / setter on the left side:

$self->attr($dummy) =~ s/pattern/string/g;

But this obviously causes an error

Cannot change non-lvalue subroutine call in Test.pm line 58, line 29

Is there a way to use Moose accessories as an lvalue subs ?

3) Use String Features

:

has 'attr' => ( is => 'rw', isa => 'Str', traits  => ['String'],
                handles => { replace_attr => 'replace'}  );

:

$self->replace_attr('pattern', 'string');

, /g.

, , , ?

+4
2

, , . /g.

$self->attr( $self->attr =~ s/pattern/string/gr );

, , , .

, /r, , Perl 5.14+.

+5

(2) MooseX:: LvalueAttributes:

package Test;
use Moose;
use MooseX::LvalueAttribute 'lvalue';
has 'attr' => ( is => 'rw', isa => 'Str', traits => [lvalue] );

:

$self->attr($dummy) =~ s/pattern/string/g;

Variable:: Magic perlsub lvalue, , "traited", , . LeoNerd ikegami .

, Moose - , .

+4

Source: https://habr.com/ru/post/1608513/


All Articles