我有以下输入
@Book{press,
author = "Press, W. and Teutolsky, S. and Vetterling, W. and Flannery B.",
title = "Numerical {R}ecipes in {C}: The {A}rt of {S}cientific {C}omputing",
year = 2007,
publisher = "Cambridge University Press"
}
我必须为 RecDescent 解析器生成器编写一个语法。输出数据应针对 xml 结构进行修改,应如下所示:
<book>
<keyword>press</keyword>
<author>Press, W.+Teutolsky, S.+Vetterling, W.+Flannery B.</author>
<title>Numerical {R}ecipes in {C}: The {A}rt of {S}cientific {C}omputing</title>
<year>2007</year>
<publisher>Cambridge University Press</publisher>
</book>
附加和重复的字段应报告为错误(带有行号的正确消息,无需进一步解析)。我试图从这样的事情开始:
use Parse::RecDescent;
open(my $in, "<", "parsing.txt") or die "Can't open parsing.txt: $!";
my $text;
while (<$in>) {
$text .= $_;
}
print $text;
my $grammar = q {
beginning: "\@Book\{" keyword fields "\}" { print "<book>\n",$item[2],$item[3],"</book>"; }
keyword: /[a-zA-Z]+/ "," { return " <keyword>".$item[1]."</keyword>\n"; }
fields: one "," two "," tree "," four { return $item[1].$item[3].$item[5].$item[7]; }
one: "author" "=" "\"" /[a-zA-Z\s\.\,\{\}\:]+/ "\"" { $item[4] =~ s/\sand\s/\+/g;
return " <author>",$item[4],"</author>\n"; }
two: "title" "=" "\"" /[a-zA-Z\s\.\,\{\}\:]+/ "\"" { $item[4] =~ s/\sand\s/\+/g;
return " <title>",$item[4],"</title>\n"; }
three: "year" "=" /[0-2][0-9][0-9][0-9]/ { return " <year>",$item[3],"</year>\n"; }
four: "publisher" "=" "\"" /[a-zA-Z\s\.\,\{\}\:]+/ "\""
{ $item[4] =~ s/\sand\s/\+/g;
return " <publisher>",$item[4],"</publisher>\n"; }
};
my $parser = new Parse::RecDescent($grammar) or die ("Bad grammar!");
defined $parser->beginning($text) or die ("Bad text!");
但我什至不知道这是否是正确的做法。请帮忙。
还有一个小问题。输入时的标签可能没有特定的顺序,但每个标签只能出现一次。我是否必须为(作者、标题、年份、出版商)的所有排列编写子规则?因为我想出了:
fields: field "," field "," field "," field
field: one | two | three | four
但它显然不会阻止重复标签。