Perl 6-単純文字列解析
2552 ワード
単純文字列解析
Perl 6を使用して、引用符による文字列をいくつかの方法で解析しました.しかし、もっときれいな方法があるかどうか知りたいです.次のテストは、文字列を作成するために用意された小型grammarです.
grammar String::Simple::Grammar {
our $quote;
rule TOP {^ $}
# Note for now, {} gets around a rakudo binding issue
token string { {} :temp $quote = $; $ }
token quote { '"' | "'" }
token quotebody { ( | . )* }
token escaped { '\\' ( $quote | '\\' ) }
}
class String::Simple::Actions {
method TOP($/) { make $.made }
method string($/) { make $.made }
method quotebody($/) { make [~] $0.map: {$^e.made or ~$^e} }
method escaped($/) { make ~$0 }
}
use Test;
plan(5);
my $grammar = ::String::Simple::Grammar;
my $actions = String::Simple::Actions.new();
# The semantics of our string are:
# * Backslash before a backslash is backslash
# * Backslash before a quote of the type enclosing the string is that quote
# * All chars including backslash are otherwise literal
ok $grammar.parse(q{"foo"}, :$actions), "Simple string parsing";
is $grammar.parse(q{"foo"}, :$actions).made, "foo", "Content of matched string";
is $grammar.parse(q{"f\oo"}, :$actions).made, "f\\oo", "Content of matched string";
is $grammar.parse(q{"f\"oo"}, :$actions).made, "f\"oo", "Content of matched string";
is $grammar.parse(q{"f\\\\oo"}, :$actions).made, "f\\oo", "Content of matched string";
別のバージョン:
grammar String::Simple::Grammar {
rule TOP {^ $}
# Note for now, {} gets around a rakudo binding issue
token string { {} )> $ }
token quote { '"' | "'" }
token quotebody($quote) { ( | . )* }
token escaped($quote) { '\\' ( $quote | '\\' ) }
}
class String::Simple::Actions {
method TOP($/) { make $.made }
method string($/) { make $.made }
method quotebody($/) { make [~] $0.map: {..made // .Str} }
method escaped($/) { make ~$0 }
}
違いは次のとおりです.
quotebody
メソッドは、定義のために1元のポイント番号と//
を使用します.テキスト