Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Regex in an 'if' statement [syntax]

Tags:

syntax

regex

perl

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/) {..}

??

like image 318
snoofkin Avatar asked Apr 08 '11 10:04

snoofkin


2 Answers

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.

like image 75
UncleZeiv Avatar answered Sep 18 '22 06:09

UncleZeiv


for ($data) {
    if (/regex/ && /secondregex/) {...}
}
like image 31
Eugene Yarmash Avatar answered Sep 21 '22 06:09

Eugene Yarmash