Is possible to use next inside of map in perl?

Viewed 170

I would like to parse only headers name in 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));
}

So my perl script looks like this:

#!/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";

gives error:

Can't "next" outside a loop block 

so is next possible in map? if so, how to fix my case?

1 Answers

A given iteration of map can return any number of scalars including zero.

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

A match with captures in list context returns the captured text on a match, and nothing on a failed match. As such, the above can be simplified.

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