BackPacker777
BackPacker777

Reputation: 683

How do I use a Moose Type as a regex match expression?

I have the following type in my class file:

has 'cardNumber' => (is => 'ro', isa => 'Int', required => 1);

I am trying to do the following:

foreach $_ (@accountsInfo) {
      if ($_ =~ m/^$self->cardNumber()/) {
            $self->pushing(split(/,/, $_));
            $self->invokeAccount();
      }
 }

But I can't get it to test properly. If I manually type in the number I am looking for in the regex slashes it works perfectly. Can you please help me to use the cardNumber Type?

Upvotes: 1

Views: 268

Answers (2)

amon
amon

Reputation: 57640

Perl's interpolation rules state that arrays ("@foo") and scalars ("$bar"), as well as (a) lookups of values in hashes ("$baz{bar}") or arrays ("$foo[1]"), and (b) dereferences of the previous cases ("@$foo, $$bar, $baz->{bar}, $foo->[1]") are interpolated into double quoted strings.

Function calls, and per extension method calls, are not interpolated.

You can interpolate arbitrary code into strings by using a trick of dereferencing an anonymous reference. Usually, you want an arrayref:

"foo @{[ expressions; ]} bar"; # interpolating anon hashref

but scalar refs work as well (they are 1 character longer).

"foo ${\( expressions; )}" # interpolating anon scalar ref

However, you should consider caching the value you want to interpolate in a scalar variable:

my $cardNumber = $self->cardNumber;
for (@accountsInfo) {
  if (/\A\Q$cardNumber\E/) {
    $self->pushing(split /,/);
    $self->invokeAccount();
  }
}

Additional note: I stripped out unneccessary parens and mentions of $_ from that code snippet. Also, I escaped the characters in $cardNumber so that they match literally, and aren't treated as a regex.

Upvotes: 5

Julian Fondren
Julian Fondren

Reputation: 5619

Print it to see what you're trying to match. You'll get output like SOMECLASS=HASH(0x6bbb48)->foo(). A solution:

/^@{[$self->cardNumber()]}/

Upvotes: 1

Related Questions