用于C程序的perl匹配函数

时间:2015-02-19 16:39:21

标签: perl

尝试在C程序中使用perl API函数。找不到正则表达式匹配的函数。希望在以下程序中有像regexmatch这样的函数。

#include <EXTERN.h>               /* from the Perl distribution     */
#include <perl.h>                 /* from the Perl distribution     */
#include <sys/time.h>

typedef unsigned long ulong;

static PerlInterpreter *my_perl;  /***    The Perl interpreter    ***/


int main(int argc, char **argv, char **env) {
    int numOfArgs = 0;
    PERL_SYS_INIT3(&numOfArgs, NULL, NULL);
    my_perl = perl_alloc();
    perl_construct(my_perl);
    SV* str = newSVpv(argv[1], strlen(argv[1]));
    if (regexmatch(str, "/hi (\S+)/")) {
        printf("found a match\n");
    }   
    return 0;
}

我知道可以使用pcre库,只是想知道是否可以从perl库中获取它(ubuntu 12.04上的libperl.so.5.14.2)

谢谢!

更新1: 做了一些谷歌搜索,并得到了以下简单的程序编译。但当我将程序作为./a.out ping pin运行时,它在“pregcomp”函数中给出了“Segmentation fault”。不知道为什么。

#include <EXTERN.h>               /* from the Perl distribution     */
#include <perl.h>                 /* from the Perl distribution     */
#include <sys/time.h>
#include <embed.h>

typedef unsigned long ulong;

static PerlInterpreter *my_perl;  /***    The Perl interpreter    ***/

struct REGEXP * const engine;

int main(int argc, char **argv, char **env) {
    int numOfArgs = 0;
    PERL_SYS_INIT3(&numOfArgs, NULL, NULL);
    my_perl = perl_alloc();
    perl_construct(my_perl);

    SV* reStr = newSVpv(argv[2], strlen(argv[2]));
    printf("compiling regexp\n");
    REGEXP * const compiled_regex = pregcomp(reStr, 0);
    printf("execing regexp\n");
    int len = strlen(argv[1]);
    pregexec(compiled_regex, argv[1], argv[1] + len, argv[1], 5, NULL, 0);
    return 0;
}

1 个答案:

答案 0 :(得分:4)

不要惹恼Perl的私人内部。调用使用匹配运算符的Perl子。

假设您之前在解释器中编译了以下内容(使用eval_pv),

sub regex_match { $_[0] =~ $_[1] }

然后你可以打电话

static bool regex_match_sv(SV* str, SV* re) {
    dSP;
    bool matched;
    ENTER;
    SAVETMPS;
    PUSHMARK(SP);
    XPUSHs(str);
    XPUSHs(re);
    PUTBACK;
    call_pv("regex_match", G_SCALAR);
    SPAGAIN;
    matched = SvTRUE(POPs);
    PUTBACK;
    FREETMPS;
    LEAVE;
    return matched;
}