CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Assignment problem with regex

 



kiojichi
New User

Sep 4, 2012, 4:22 PM

Post #1 of 3 (982 views)
Assignment problem with regex Can't Post

Hi All,

I'm having an issue getting a value assigned to a variable after a regex match, for an iP address. I'm sure I'm doing something that's clearly wrong, and obvious to most, but I'm new to Perl and I've been working on this for 2 days now. The assignment is just not happening right.

Code:


Code
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 that the regex is matching against is:

Code
1307931062: INIT: banned_ip add 208.67.219.132 for FreeGate


In the match and substitution line, it appears that the regex is matching just fine, but when I try to send the matched data to a variable ($ipaddress in this case) it always fails. Is there a better way to do this?

Thanks.


kiojichi
New User

Sep 4, 2012, 5:06 PM

Post #2 of 3 (977 views)
Re: [kiojichi] Assignment problem with regex [In reply to] Can't Post

This question was answered for me by Jon Purdy at another site. Just pasting the answer here if its useful for someone in the future:

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/;
#


BillKSmith
Veteran

Sep 4, 2012, 8:26 PM

Post #3 of 3 (970 views)
Re: [kiojichi] Assignment problem with regex [In reply to] Can't Post

Even better to use a module. Less chance of false matches.

Code
use Regexp::Common; 
sub block_match {
my $RE = $RE{net}{IPv4}{dec};
my ($line_instance_b) = @_;
my $ipaddress;
if ( $line_instance_b =~ /banned_ip|Found UltraSurf Signature|ip_block / )
{
($ipaddress) = $line_instance_b =~ /$RE/;
print "Found ip address: ", $ipaddress, "in the following line: \n",
$line_instance_b;
}
else { print "Not a block line: \n", $line_instance_b, "\n" }
}

Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives