Perl Regex in an 'if' statement [syntax]

58,025

Solution 1

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.

Solution 2

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

Solution 3

Only one line using smart match:

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

Solution 4

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/

Solution 5

To add to the list of ways to put $data into $_:

if ( grep { m/regex/ && m/secondregex/ } $data ) {...}
Share:
58,025

Related videos on Youtube

snoofkin
Author by

snoofkin

Developer...............C/C++.......Perl.......XSLT......Bash.......etc.... Concentrating mainly on Perl & C++ and Qt.

Updated on July 09, 2022

Comments

  • snoofkin
    snoofkin almost 2 years

    Up to now, if I wanted to group together several regex's within an if statement, I did it this way:

    my $data =...
    if ($data =~ m/regex/ && $data =~ m/secondregex/) {...}
    

    Is there a shortcut (and I'm sure there is; it's Perl!) to avoid repeating $data, something like:

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

    ??

    • halfdan
      halfdan about 13 years
      Can you give an example pattern? You should be able to combine both patterns into one.
    • BoltClock
      BoltClock about 13 years
      If you combined them into a single regex you would need to combine all the possible orders in which the subpatterns can appear in a single string, generating even more complex regexes to test against. For two regexes it would be m/^(?:.*regex.*secondregex .*)|(?:.*secondregex.*regex.*)$/ For three or more, it gets ugly.
  • Eugene Yarmash
    Eugene Yarmash about 13 years
    You may want to localize $_: local $_ = $data
  • Nick Dixon
    Nick Dixon about 13 years
    This looks cleaner to me than explicitly assigning to a localized $_ - it's analogous to "with" and similar constructs in other languages.
  • BillMan
    BillMan over 7 years
    Assigning to an implicit variable seems like a bit of a hack to me.

Related