本帖最后由 sxw 于 2020-5-19 23:18 编辑
使用 Perl 6(现在叫 Raku):- # 定义 Grammar
- unit grammar IPConfig::Grammar;
-
- token TOP { <section>+ %% \n* }
- token section {
- <header>
- \n
- <config>+
- }
-
- token header { ^^ \N+ \n }
- token config { ^^ \s+ \N+ $$ \n* }
-
-
- # 定义 Action
-
- unit class IPConfig::Action;
-
- method TOP($/) {
- make $/<section>».made;
- }
-
- method section($/) {
- my $configs = $/<config>».made;
- if $configs.elems > 0 {
- make ~$/<header> ~ $configs.join("");
- } else {
- make Empty;
- }
- }
-
- method header($/) {
- make ~$/;
- }
-
- method config($/ is copy) {
- my $text = ~$/;
- if $text.contains(/'描述' | '物理地址' | IPv[4|6] ' ' 地址 | '子网掩码' | DNS ' ' 服务器/) {
- $/.make(~$/);
- } else {
- make Empty;
- }
- }
-
- # 调用
-
- use lib '.';
- use IPConfig::Grammar;
- use IPConfig::Action;
-
- my $ipconfig = IPConfig::Grammar.parsefile(
- "ifconfig.txt",
- :actions(IPConfig::Action)
- ).made;
-
- .Str.say for @$ipconfig;
复制代码
|