2

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
1
  • In list context a match returns a list of the captures, you can do my ($ipaddress) = $line_instance_b =~ /…/ instead. Additionally, the pedant in me must point out that your regex completely precludes the possibility of IPv6 addresses, which eventually will bite you. Commented Sep 5, 2012 at 2:10

1 Answer 1

6

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/;
#                                         ^~~~~~~~~~~~~~~~~~~~^
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Thanks Jon. That did work, and now I know what to read over again as well. Thanks for taking the time :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.