2017-11-12 8 views
2

私はBibTeX著者フィールドを解析し、それを別々の著者に分割しようとしています。これは、各著者のイニシャルを書き直すのに役立ちます。ここでは、最小限の例です:文法で以前に一致した項目を参照する方法は?

use v6; 

my $str = '{Rockhold, Mark L and Yarwood, RR and Selker, John S}'; 

grammar BibTexAuthor { 
    token TOP { 
     <all-text> 
    } 
    token all-text { 
     '{' <authors> '}' 
    } 
    token authors { 
     [<author> [' and ' || <?before '}'>]]+ 
    } 
    token author { 
     [<-[\s}]> || [' ' <!before 'and '>]]+ 
    } 
} 

class BibTexAuthor-actions { 
    method TOP($/) { 
     say $/; 
     print "First author = "; 
     say $<author>.made[0]; 
     make $/.Str; 
    } 
    method all-text($/) { 
     make $/.Str; 
    } 
    method authors($/) { 
     make $/.Str; 
    } 
    method author($/) { 
     make $/.Str; 
    } 
} 
my $res = BibTexAuthor.parse($str, actions => BibTexAuthor-actions.new).made; 

出力

「{Rockhold, Mark L and Yarwood, RR and Selker, John S}」 
all-text => 「{Rockhold, Mark L and Yarwood, RR and Selker, John S}」 
    authors => 「Rockhold, Mark L and Yarwood, RR and Selker, John S」 
    author => 「Rockhold, Mark L」 
    author => 「Yarwood, RR」 
    author => 「Selker, John S」 
First author = Nil 

なぜTOP方法で最初の著者を抽出することができないのですか?

+0

'メソッドの作者($ /)を取得するために言うことができる{(*。製) .MAP @作る}' –

+0

@BradGilbertのおかげで提案のために、私はその仕事をすることはできません。私の 'method authors 'をあなたの提案に置き換えた場合、私は最初の著者のために' Nil'という出力を得ます。 –

+2

$ [0]; – Holli

答えて

4

なぜ私は最初の著者を抽出することはできませんよのいずれかを試すことができますTOPメソッド?

アクションメソッドで実際にデータを抽出していないためです。あなたがしているのは、一致の文字列を$/.madeに添付することです。これは実際に最後に必要なデータではありません。

最後に別の著者を追加する場合は、アクションメソッドの著者の配列makeを指定する必要があります。例えば:

use v6; 

my $str = '{Rockhold, Mark L and Yarwood, RR and Selker, John S}'; 

grammar BibTexAuthor { 
    token TOP { 
     <all-text> 
    } 
    token all-text { 
     '{' <authors> '}' 
    } 
    token authors { 
     [<author> [' and ' || <?before '}'>]]+ 
    } 
    token author { 
     [<-[\s}]> || [' ' <!before 'and '>]]+ 
    } 
} 

class BibTexAuthor-actions { 
    method TOP($/) { 
     make { authors => $<all-text>.made }; 
    } 
    method all-text($/) { 
     make $/<authors>.made; 
    } 
    method authors($/) { 
     make $/<author>».made; 
    } 
    method author($/) { 
     make $/.Str; 
    } 
} 
my $res = BibTexAuthor.parse($str, actions => BibTexAuthor-actions.new).made; 

say $res.perl; 

プリント

${:authors($["Rockhold, Mark L", "Yarwood, RR", "Selker, John S"])} 

今最上位マッチの.madeauthorsキーが配列を保持しているハッシュです。あなたが最初の作者にアクセスしたい場合は、あなたが今

say $res<authors>[0]; 

Rockhold, Mark L

4
$<all-text><authors><author>[0]; 

文法は今までどのように動作しているかわかりません。私はあなたがしているように言語を学んでいます。

しかし、データ構造を見るだけで、それがツリーであり、そのツリー内であなたが探している価値がどこにあるのかを理解するのは簡単です。

あなたは

dd $someStructure; 
say $someStructure.perl; 

を言うことによって、出力の任意のデータ構造をすることができますし、それが読めない見つけた場合、あなたはDumper Modules

関連する問題