在Perl中从给定条件中提取边界
我有一个矩形区域,由某些条件描述如下:
I have a square-shape zone described by some conditions as follows:
x < b && x >= a && y < d && y >= c
我想提取右上角和左下角的坐标. (假设整个条件在$ cond中给出.此外,将对存储在两个列表@xy_b
和@xy_t
中).对于此示例:@xy_b = (a , c)
和@xy_t = (b, d)
.
I would like to extract the top-right and bottom-left corners coordinates. (Let's assume that the whole condition is given in $cond. Also, store the pairs in two lists @xy_b
and @xy_t
). For this example: @xy_b = (a , c)
and @xy_t = (b, d)
.
备注
- 条件的顺序可能会混乱(例如
y < d && x >= a && x < d && y >= c
). - 同时预期
x < a
和a > x
- 没有像
b =< x < a
这样的条件. - 预期条件,例如:
x <= b && x >= a
或x < b && x > a
(除非您有更好的约定来区分它们,否则请进行相同的处理). -
预计可能会错过部分或全部条件.如果发出其中一个条件,则应相应地考虑零或无穷大.例如,在以下条件集中:
- The order of conditiones might be scrambled (e.g.
y < d && x >= a && x < d && y >= c
). - Expect both
x < a
anda > x
- There is no condition like
b =< x < a
. - Expect conditions like:
x <= b && x >= a
orx < b && x > a
(treat them the same unless you have a better convention to distinguish the,). Expect some or all of the conditions may be missed. If one of the conditions is issued it should be consider correspondingly zero or infinity. For example in the following condition set:
x < b && x >= a && y >= c
y
的上限必须为无穷大.如果缺少下限,则应将其视为零.
the upper limit for y
must be infinity. If the lower limit is missing, it should be considered zero.
使这个问题复杂化非常容易.
It would be very easy to over complicate this problem.
但是,以下是概念证明,试图将其分解为最简单的正则表达式.
However, the following is a proof of concept that attempts to break this down into the simplest regular expressions.
- 如果忽略等号,只需将其删除.
- 分别匹配每个变量边界.
- 现在假设每个边界只能是另一个变量.
- 对于不匹配的规则,目前还没有其他验证.
以下是演示此逻辑的代码:
Here is the code that demonstrates this logic:
use strict;
use warnings;
while (<DATA>) {
# Remove all equals signs since we ignore that data.
s{=(?=[<>])|(?<=[<>])=}{}g;
die "Invalid equal sign found in $_" if /=/;
my %boundary;
for my $var (qw(x y)) {
my $min = /\b$var\b \s* > \s* (\w+)/x || /(\w+) \s* < \s* \b$var\b/x ? $1 : 0;
my $max = /\b$var\b \s* < \s* (\w+)/x || /(\w+) \s* > \s* \b$var\b/x ? $1 : 'Inf';
$boundary{$var} = {
min => $min,
max => $max,
}
}
print "($boundary{x}{min}, $boundary{y}{min}) to ($boundary{x}{max}, $boundary{y}{max})\n\n"
}
__DATA__
x < b && x >= a && y < d && y >= c
y < d && x >= a && x < d && y >= c
x < b && x >= a && y >= c
输出:
(a, c) to (b, d)
(a, c) to (d, d)
(a, c) to (b, Inf)