use v5.12;
use warnings;

# demo for:
# http://stackoverflow.com/questions/17039670/vertical-regex-matching-in-an-ascii-image


my $r = qr/
^                        # beginning of line
(?:
    .                    # any character except \n
    (?=                  # lookahead
        .*+\n            # go to next line
        ( \1?+ . )       # add a character to the 1st capturing group
        .*+\n            # next line
        ( \2?+ . )       # add a character to the 2nd capturing group
    )
)*?                      # repeat as few times as needed
X .*+\n                  # X on the first line and advance to next line
\1?+                     # if 1st capturing group is defined, use it, consuming exactly the same number of characters as on the first line
X .*+\n                  # X on the 2nd line and advance to next line
\2?+                     # if 2st capturing group is defined, use it, consuming exactly the same number of characters as on the first line
X                        # X on the 3rd line
/xm;


my @maps = split /\n\n/, <<'MAPS';
X
X
X

..X....
..X....
..X....

..X.X..
..X.X..
....X..

..X....
..X....
...X...

..X....
...X...
..X....

....X..
.X..X..
.X.....
MAPS


for(my $i = 0; $i < @maps; ++$i){
    my $map = $maps[$i];
	my $m = $map =~ /$r/;
	say "map $i:";
	say "$map\n";
	
	say $m ? "MATCHED:": "no match";
	say $& if $m;
	
	say "---------------";
}
