Perl Regex in an 'if' statement [syntax]

Use the default variable $_ like this:

$_ = $data;
if ( m/regex/ && m/secondregex/ ) {..}

as regular expressions act on $_ by default (as many other things in Perl).

Just be certain that you are not in a block where $_ is automatically populated and you will need to use it later in this block. Once it's overwritten it's gone.


One more suggestion. Depending on how long your list of regexes you need to match in one if, and how often you need to do this kind thing, it would make a lot of sense to turn this into a subroutine.

Inspired by ruby's every:

sub matchesAll ($@) {
  my $string = shift;
  my $result = 1;
  foreach $_ (@_) {
    $result &&= $string =~ $_;
  }
  $result;
}

And then do

if (matchesAll $data, $regex1, $regex2, $regex3, $regex4) ...

Note: this requires all regexs be compiled for future use using qr// $regex1 = qr/regex1/


for ($data) {
    if (/regex/ && /secondregex/) {...}
}

Only one line using smart match:

use 5.010;
if ($data ~~ [qr/regex1/,qr/regex2/]) { ... }

Tags:

Syntax

Regex

Perl