如果用户被允许在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来变异和执行代码可以使写和使用强大的滤波器程序变得简单明了。