在Perl中从给定条件中提取边界 [英] Extracting boundaries out of given condition in Perl

查看:114
本文介绍了在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 < aa > x
  • 没有像b =< x < a这样的条件.
  • 预期条件,例如:x <= b && x >= ax < b && x > a(除非您有更好的约定来区分它们,否则请进行相同的处理).
  • 预计可能会错过部分或全部条件.如果发出其中一个条件,则应相应地考虑零或无穷大.例如,在以下条件集中:

  • The order of conditiones might be scrambled (e.g. y < d && x >= a && x < d && y >= c).
  • Expect both x < a and a > x
  • There is no condition like b =< x < a.
  • Expect conditions like: x <= b && x >= a or x < 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.

  1. 如果忽略等号,只需将其删除.
  2. 分别匹配每个变量边界.
  3. 现在假设每个边界只能是另一个变量.
  4. 对于不匹配的规则,目前还没有其他验证.

以下是演示此逻辑的代码:

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)

这篇关于在Perl中从给定条件中提取边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆