Difference between two regular expressions

N

Neil Shadrach

Why do the two 'print' lines behave differently in the following?

#!/usr/bin/perl -w

use strict;
use warnings;

$/.=$/;

while(<DATA>)
{
print "\nA:1[$1]\nA:2[$2]" if /bindings: (?:(.+ => .+)\n?\s*)(?:(.+ => .+\n?\s*))/;
print "\nB:1[$1]\nB:2[$2]" if /bindings: (?:(.+ => .+)\n?\s*){2}/;
}

__DATA__
community: public
enterprise: 9.9.9.9.9.9.999.9.9.9.9
agent addr: 999.99.99.999
agent name: ab.cd.ef.gh
generic ID: 9
specific ID: 999
uptime: 9:99:99
bindings: 9.9.9.9.9.9.9.9.9 => Warning: /local/file has reached maximum size
9.9.9.9.9.9.999.9.9.9.9.9 => local_storage
###
!/tmp/demo.pl

A:1[9.9.9.9.9.9.9.9.9 => Warning: /local/file has reached maximum size]
A:2[9.9.9.9.9.9.999.9.9.9.9.9 => local_storage

]Use of uninitialized value in concatenation (.) at /tmp/demo.pl line 11, <DATA> chunk 1.

B:1[9.9.9.9.9.9.999.9.9.9.9.9 => local_storage]
B:2[]
 
A

Anno Siegel

Neil Shadrach said:
Why do the two 'print' lines behave differently in the following?

#!/usr/bin/perl -w

use strict;
use warnings;

$/.=$/;

while(<DATA>)
{
print "\nA:1[$1]\nA:2[$2]" if /bindings: (?:(.+ => .+)\n?\s*)(?:(.+
=> .+\n?\s*))/;
print "\nB:1[$1]\nB:2[$2]" if /bindings: (?:(.+ => .+)\n?\s*){2}/;
}

__DATA__
community: public
enterprise: 9.9.9.9.9.9.999.9.9.9.9
agent addr: 999.99.99.999
agent name: ab.cd.ef.gh
generic ID: 9
specific ID: 999
uptime: 9:99:99
bindings: 9.9.9.9.9.9.9.9.9 => Warning: /local/file has reached
maximum size
9.9.9.9.9.9.999.9.9.9.9.9 => local_storage
###
!/tmp/demo.pl

A:1[9.9.9.9.9.9.9.9.9 => Warning: /local/file has reached maximum size]
A:2[9.9.9.9.9.9.999.9.9.9.9.9 => local_storage

]Use of uninitialized value in concatenation (.) at /tmp/demo.pl line
11, <DATA> chunk 1.

B:1[9.9.9.9.9.9.999.9.9.9.9.9 => local_storage]
B:2[]

The first patten contains two pairs of capturing parentheses, the second
contains only one. A regex sets only as many $<n> variables as it
captures.

Your problem is obfuscated by a lot of accidential circumstances,
like multiline matching with a non-standard $/, and more. Reduce
it to the simplest terms that still exhibit the problem:

$_ = 'tuttut';

print "$1, $2\n" if /(tut)(tut)/;
print "$1, $2\n" if /(tut){2}/;

Try this technique before posting -- you'll either solve your problem
yourself, or you'll be able to present a much more appealing question.

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top