perl6语法action class method好像没有继承,named capture好像没发

perl6 Grammar action class method seems not inherited, named capture seems not made

我正在尝试解析一个 csv 文件来做一些简单的事情:提取姓氏、ID 和生日,并将生日格式从 m/d/yyyy 更改为 yyyymmdd。

(1) 我用命名捕获来庆祝生日,但似乎没有调用命名捕获方法来制作我想要的东西。

(2) 继承语法操作方法似乎不适用于命名捕获。

我做错了什么?

my $x = "1,,100,S113*L0,35439*01,John,JOE,,,03-10-1984,47 ELL ST #6,SAN FRANCISCO,CA,94112,415-000-0000,,5720,Foo Bar,06-01-2016,06-01-2016,Blue Cross,L,0,0";

# comma separated lines
grammar insurCommon {
    regex aField  { <-[,]>*? }
    regex theRest { .* }
}    

grammar insurFile is insurCommon {
    regex TOP { <aField> \,\,  # item number
        <aField> \,            # line of business
        <aField> \,            # group number
        <ptID=aField> \,       # insurance ID, 
        <ptLastName=aField> \, # last name, 
        <aField> \,\,\,        # first name
        <ptDOB=aField> \,      # birthday
        <theRest> }
}

# change birthday format from 1/2/3456 to 34560102
sub frontPad($withWhat, $supposedStrLength, $strToPad) {
    my $theStrLength = $strToPad.chars;
    if $theStrLength >= $supposedStrLength { $strToPad; }
    else { $withWhat x ($supposedStrLength - $theStrLength) ~ $strToPad; }
}

class dateAct {
    method reformatDOB($aDOB) {
      $aDOB.Str.split(/\D/).map(frontPad("0", 2, $_)).rotate(-1).join;
    }
}

class insurFileAct is dateAct {
    method TOP($anInsurLine) {
      my $insurID = $anInsurLine<ptID>.Str;
      my $lastName = $anInsurLine<ptLastName>.Str;
      my $theDOB = $anInsurLine<ptDOB>.made; # this is not made;
      $anInsurLine.make("not yet made"); # not yet getting $theDOB to work
    }
    method ptDOB($DOB) { # ?ptDOB method is not called by named capture?
      my $newDOB = reformatDOB($DOB); # why is method not inherited
      $DOB.make($newDOB);
    }
}

my $insurAct = insurFileAct.new;
my $m = insurFile.parse($x, actions => $insurAct);

say $m.made;

输出为:

===SORRY!=== Error while compiling /home/test.pl
Undeclared routine:
    reformatDOB used at line 41

您正在尝试调用 non-existing 子例程 reformatDOB,而不是方法。

与 Java 相比,Perl6 不允许您省略调用者,即方法调用必须写成

self.reformatDOB($DOB)

此外,还有shorthand形式如

$.reformatDOB($DOB) # same as $(self.reformatDOB($DOB))
@.reformatDOB($DOB) # same as @(self.reformatDOB($DOB))
...

另外对 return 值施加上下文。

另外:为什么要重新发明轮子? Perl 6 有 Text::CSV:

https://github.com/Tux/CSV

安装:

panda install Text::CSV

或:

zef install Text::CSV

你是对的,命名捕获的名称的操作方法没有被调用。相反,它将根据匹配的事物的名称调用方法。 IE。将调用一个字段。

您可以从 TOP 操作方法中手动调用 self.ptDOB($anInsurLine<ptDOB>)