What regex will match this correctly, please?
I want to identify strings that do not end in specific text (_array). I've tried to use negative lookahead, but I can't get it working. (Note the obvious answer is to do the inverse (m{_array$}), but there's a reason I don't want to do that).
use strict;
use warnings;
while(<DATA>) {
#
## If the string does not end with '_array' print No, otherwise print Yes
m{(?!_array)$} ? print "No = " : print "Yes = ";
print;
}
__DATA__
chris
hello_world_array
another_example_array
not_this_one
hello_world
My wanted output should be:
No = chris
Yes = hello_world_array
Yes = another_example_array
No = not_this_one
No = hello_world
You need negative look behind. I.e., you want to search for the end of the string not preceded _array
.
Note that you need to chomp
the line first, as $
will match both before and after a trailing newline.
And the conditional operator is meant to return a value - it is not a shorthand for an if
statement.
use strict;
use warnings;
while (<DATA>) {
chomp;
# If the string does not end with '_array' print No, otherwise print Yes
print /(?<!_array)$/ ? "No = $_\n" : "Yes = $_\n";
}
__DATA__
chris
hello_world_array
another_example_array
not_this_one
hello_world
Output
No = chris
Yes = hello_world_array
Yes = another_example_array
No = not_this_one
No = hello_world