make empty

作者: 焉知非鱼 | 来源:发表于2018-11-15 22:34 被阅读0次
    my $str = q :to/EOF/;
    Perl6,Rust
    -- this is a comment
    Rakudo,Raku
    -- this is another comment
    Camelia,Camel
    EOF
    
    grammar MakeEmpty {
        token TOP      { ^ <sentence>+ % <comment>  $}
        token sentence { <words>+ % ',' \n   }
        token comment  { '-- ' <words>+ % ' ' \n  }
        token words    { \w+ }
    }
    
    class Action {
        method TOP($/)      { make $/.values».ast }
        method sentence($/) { make ~$/.trim   }
        method comment($/)  { make Empty }
        method words($/)    { make ~$/   }
    }
    
    my $parsed = MakeEmpty.parse($str, :actions(Action)).ast;
    .say for @$parsed;
    
    # Perl6,Rust
    # Rakudo,Raku
    # Camelia,Camel
    
    say '-' x 25;
    # ----------------------------------------------------------
    
    my $string = q :to/EOF/;
    Perl6,Rust
    -- this is a comment
    Rakudo,Raku
    -- this is another comment
    Camelia,Camel
    /* this is inline comments */
    Java,Nim
    
    Python,PHP
    EOF
    
    grammar WhiteSpace {
        rule TOP       { ^ <sentence>+ % <.ws> $ }
        token sentence { <words>+ % ',' \n       }
        token comment  { '-- ' <words>+ % ' ' \n }
        token words    { \w+ }
        token ws { \s* | <comment> | <slash-star-comment> }
        token slash-star-comment { \s* '/*' .*? '*/' \s* }
    }
    
    class SpaceAction {
        method TOP($/)      { make $/.values».ast  }
        method sentence($/) { make ~$/.trim        }
        method comment($/)  { make ~$/             }
        method words($/)    { make ~$/             }
        method slash-star-comment($/) { make ~$/   }
        method ws($/)                 { make Empty }
    }
    
    my $em = WhiteSpace.parse($string, :actions(SpaceAction)).ast;
    .say for @$em;
    
    # Perl6,Rust
    # Rakudo,Raku
    # Camelia,Camel
    # Java,Nim
    # Python,PHP
    

    参考 https://stackoverflow.com/questions/42254754/how-to-skip-unrelated-lines-when-using-perl-6-grammar-to-parse-structurized-text

    相关文章

      网友评论

        本文标题:make empty

        本文链接:https://www.haomeiwen.com/subject/aawufqtx.html