在Perl中构造查询引擎

ZDNet软件频道 时间:2004-01-29 作者:ZDNet China |  我要评论()
本文关键词:perl
如果用户被允许在Perl中用自己的语言详细的直接询问,那么Perl分析文本的能力将被大大地增强。那么我们该如何构造它呢?
本文译自TechRepublic,未经许可请勿转载

  

如果用户被允许在perl中用自己的语言详细的直接询问那么perl分析文本的能力将被大大地增强。这个技术允许记录文件的复形处理并允许其他程序的输出。

   下面的程序将执行在CSV文件上任意复形查询,比如,通过电子表格程序运行的进程。假设文件的第一行包括了文件的列表。简单的说,程序将从standard in中读取输出数据。

use strict;
use Text::ParseWords;

# get header line
my $header = <STDIN>;

# get field names
my @fieldNames = quotewords(",", 0, $header);

# strip leading & trailing spaces (if any), replace internal spaces with underscore
@fieldNames = map {s/^s+//; s/s+$//; s/s+/_/g; $_} @fieldNames;

my @fields; # where field data will be stored

# create access functions
for (my $i = 0; $i < @fieldNames; $i++)
{
    no strict 'refs';

    my $name = $fieldNames[$i];

    eval "sub $name () { $fields[$i] }";     # create access subroutine
    *{lc $name} = *{uc $name} = $name; # make upper and lower case aliases
}

# compile user's query
my $code = "sub Query { " . join(" and ", @ARGV) . " }";
eval $code.1 or die "Error: $@ In query string: $code ";

# print the header line (field names)
print $header;

# process each line
while (<STDIN>)
{
    @fields = quotewords(",", 0, $_);
    print if Query();
}

   使用perl来变异和执行代码可以使写和使用强大的滤波器程序变得简单明了。



责任编辑:李宁

欢迎评论投稿

百度大联盟认证黄金会员Copyright© 1997- CNET Networks 版权所有。 ZDNet 是CNET Networks公司注册服务商标。
中华人民共和国电信与信息服务业务经营许可证编号:京ICP证010391号 京ICP备09041801号-159
京公网安备:1101082134