我只想解析 main.c
中的标题名称:
#include "foo.h"
#include "bar.h"
#include <stdio.h>
int add(int a,int b){ return a+b; }
int sub(int a, int b){ return a-b; }
int main(){
printf("%i\n",add(1,2));
}
所以我的 perl 脚本如下所示:
#!/usr/bin/perl
open MAIN, $ARGV[0];
@ar = map { /#include "([^"]+)"/ ? $1 : next } <MAIN>;
#this one works (next inside for-loop, not map-loop)
for(<MAIN>){
if(/#include "([^"]+)"/){
push @ar2, $1;
} else {
next;
}
}
print "@ar\n";
print "@ar2\n";
给出错误:
Can't "next" outside a loop block
那么 next
是否可以在 map
中使用?如果是这样,如何解决我的问题?
最佳答案
map
的给定迭代可以返回任意数量的标量,包括零。
my @ar = map { /#include "([^"]+)"/ ? $1 : () } <MAIN>;
在列表上下文中使用捕获的匹配在匹配时返回捕获的文本,在匹配失败时返回任何内容。因此,上述内容可以简化。
my @ar = map { /#include "([^"]+)"/ } <MAIN>;
关于arrays - 可以在 perl 中使用 map 内部的 next 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63220938/