2

So I'm calling C code from inside mid pattern (using (?{ and sometimes (??{) from Perl.

Anyway I want to get the values of named captures the same way as using $+{name}.

Is this possible?

AnArrayOfFunctions
  • 3,452
  • 2
  • 29
  • 66
  • 1
    You can use something like `get_hv("%", 0)`, but a better approach might be to pass `\%+` as an argument. – ikegami Sep 11 '21 at 14:41

1 Answers1

2

Here is an example, where I pass a reference to %+ to the XSUB:

Rx.xs:

#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

SV *get_hash_sv(HV *hash, const char *key) {
    SV * key_sv = newSVpv (key, strlen (key));
    int value;
    if (hv_exists_ent (hash, key_sv, 0)) {
        HE *he = hv_fetch_ent (hash, key_sv, 0, 0);
        return HeVAL (he);
    }
    else {
        croak("The hash key for '%s' doesn't exist", key);
    }
}

MODULE = My::Rx  PACKAGE = My::Rx
PROTOTYPES: DISABLE

void
foo(hash)
    HV *hash
    CODE:
         SV *sv = get_hash_sv(hash, "count");
         STRLEN len;
         char *str = SvPV(sv, len);
         printf("<%.*s>\n", len, str);

test.pl

use feature qw(say);
use strict;
use warnings;
use ExtUtils::testlib;
use My::Rx;
my $str = "a 34 b 54";
my @res = $str =~ /(?<count>\d+)(?{My::Rx::foo(\%+)})/g;

Output:

<34>
<54>
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174