user1647568
user1647568

Reputation: 23

Regex to variable assignment fails in Perl

I am wondering why the following fails to assign the value (the ip address) of the regex match to the $ipaddress variable after it is matched. I've tried a number of recommended methods (I'm new to Perl obviously), but they've all failed. When performing matches, is it not true that each match is stored in the $1 variables, which range from 1-9, so that the first is, by default, $1?

Code is:

sub block_match {

  my $line_instance_b = $_[0];
  my $ipaddress;

  if ( $line_instance_b =~ /banned_ip|Found UltraSurf Signature|ip_block / ) {
    $ipaddress = $1 if ($line_instance_b =~ /\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b/);
    print "Found ip address: ", $ipaddress, "in the following line: \n",
    $line_instance_b;
  }
  else {
    print "Not a block line: \n", $line_instance_b, "\n"
  }
}

The line it is matching against is:

INIT: banned_ip add 208.67.219.132 for FreeGate

Upvotes: 2

Views: 358

Answers (1)

Jon Purdy
Jon Purdy

Reputation: 54971

You’re using a non-capturing group, (?:...), which is never assigned to a match variable.

Wrap the (?:[0-9]{1,3}\.){3} part of the expression in () to capture into $1:

$ipaddress = $1 if $line_instance_b =~ /\b((?:[0-9]{1,3}\.){3})[0-9]{1,3}\b/;
#                                         ^~~~~~~~~~~~~~~~~~~~^

Upvotes: 6

Related Questions