字符串替换在perl中不起作用

Abh*_*rni 0 regex perl

给定文本是'C'样式结构 -

    struct mystruct {
        int a[100];
        int b[10*10];
        int c[10*5+(25*2)];
        int d[10^2];
    }
Run Code Online (Sandbox Code Playgroud)

逐行读取文本并评估每个数组中的元素数量,并使用元素计数重新声明数组.

结果应如下打印: -

    struct mystruct {
        int a[100];
        int b[100];
        int c[100];
        int d[100];
    }
Run Code Online (Sandbox Code Playgroud)

字符串替换后对我不起作用 -

    if ($line =~ m/.*?\[(.*?)\]/) {
        $answer = eval ($1);
        $line =~ s/$1/$answer/g;
    }
Run Code Online (Sandbox Code Playgroud)

替换不起作用,所有评估元素计数的$ line保持不变.

TLP*_*TLP 5

直接在替换中进行评估:

$line =~ s/(?<=\[)   # assert a square bracket behind
           ([^]]*)   # capture string of non-brackets
           (?=\])    # assert square bracket after
          /$1/eex;   # double evaluate the variable
Run Code Online (Sandbox Code Playgroud)

双重评估是必要的,因为第一个评估将变量转换为字符串,然后评估字符串.

虽然你会遇到麻烦10^2,就像^二进制XOR运算符一样,而不是指数运算符**.