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

标签 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 中使用?如果是这样,如何解决我的问题?

最佳答案

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

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

在列表上下文中使用捕获的匹配在匹配时返回捕获的文本,在匹配失败时返回任何内容。因此,上述内容可以简化。

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

关于arrays - 可以在 perl 中使用 map 内部的 next 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63220938/

相关文章:

数组的 Javascript 循环错误

c# - 使用 Newtonsoft.Json 反序列化 Json 数组

c - 如何在没有 clock_t 或定时器的情况下在 C 中执行时间循环?

java - 使用循环内初始化的对象/变量?

java.lang.UnsupportedOperationException 但没有 Arrays.asList()

c - 预期为 'double **' 但参数的类型为 'double (*)[2]'

c# - 如何在循环外访问字符串数组

macos - 在 mac 10.9 中安装 libgd 时出错

perl - 如何获取具有给定属性的所有 Unicode 字符的列表?

c - 在 Perl XS 中使用 64 位整数