milanHrabos
milanHrabos

Reputation: 1975

How to apply negative regex on array in perl?

Having this:

foo.pl:

#!/usr/bin/perl -w
@heds = map { /_h.+/ and s/^(.+)_.+/$1/ and "$_.hpp" } @ARGV;
@fls = map { !/_h.+/ and "$_.cpp" } @ARGV;

print "heds: @heds\nfls: @fls";

I want to separate headers from source files, and when I give input:

$./foo.pl a b c_hpp d_hpp
heds: e.hpp f.hpp
fls: e.cpp f.cpp a.cpp b.cpp

The headers are correctly separated, however the files are taken all. Why? I have applied the negative regex !/_h.+/ in the mapping so the files with *_h* should not be taken in account, but they are. Why so? and how to fix it?

Does not work even this:

@fls = map { if(!/_h.+/){ "$_.cpp" } } @ARGV;

still takes every files, despite the condition

Upvotes: 0

Views: 109

Answers (1)

monok
monok

Reputation: 585

The map { } for @heds includes a substitution on the $1 argument and changes it. Just reorder the mapppings to avoid the effect on @fls and you get the desired result. Though, if you need to access @ARGV after these mappings it is not the original @ARGV anymore, like in your example code.

#!/usr/bin/perl -w
@fls = map { !/_h.+/ and "$_.cpp" } @ARGV;
@heds = map { /_h.+/ and s/^(.+)_.+/$1/ and "$_.hpp" } @ARGV;

print "heds: @heds\nfls: @fls\n"; 

Upvotes: 1

Related Questions