Correct way to use Moose class attribute in regex?

Now I know that the correct way to access class attributes Mooseis to ALWAYS go through the access method that is automatically generated Moose.

See Frido's answer to my previous question for reasons.

However, this raises a new question ... How do you guarantee that class attributes are Mooseprocessed correctly in regular expressions?


Follow these steps:

Person.pm

package Person;

use strict;
use warnings;
use Moose;

has 'name' => (is => 'rw', isa => 'Str');
has 'age'  => (is => 'rw', isa => 'Int');

# Make package immutable
__PACKAGE__->meta->make_immutable;

test.pl

#!/usr/bin/perl

use strict;
use warnings;
use Person;

my $person = Person->new(
    name => 'Joe',
    age  => 23,
);

my $age = 23;

# Access age the "proper" way
if ($age =~ m/$person->age()/) {
    print "MATCH 1!\n";
}

# Access age the "improper" way
if ($age =~ m/$person->{age}/) {
    print "MATCH 2!\n";
}

This code outputs the following:

MATCH 2!

Perl doesn't seem to parse the accessor method correctly when placed in a regex ... What is the proper way to handle this?

I know that I can just do this:

my $compare_age = $person->age();
if ($age =~ m/$compare_age/) {
    # MATCH!
}

, ?

0
1

, /$compare_age/ , 23 =~ /2/. :

$age =~ /^\Q$compare_age\E\z/

.

$age =~ /^\Q${\( $person->age() )}\E\z/

, , :

$age == $person->{age}
+1

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


All Articles