可以在perl中的map内使用next吗?

时间:2020-08-02 20:55:46

标签: arrays loops perl map-function

我只想解析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吗?如果是这样,如何解决我的情况?

1 个答案:

答案 0 :(得分:8)

给定的map迭代可以返回任意数量的标量,包括零。

my @ar = map { /#include "([^"]+)"/ ? $1 : () } <MAIN>;

在列表上下文中具有捕获的匹配项在匹配项中返回捕获的文本,而在失败的匹配项中不返回任何内容。因此,可以简化以上操作。

my @ar = map { /#include "([^"]+)"/ } <MAIN>;
相关问题