Make perl regex search exit with failure if not found

2

With grep I get a failure return code/exit status if no result is found.

How can I do the same thing with perl?

Basically, I would like to change the following so that it exits with status 1 if no match is found.

echo foo | perl -nle'print if m{bar}'

hpique

Posted 2014-12-04T04:12:37.527

Reputation: 263

Answers

1

Quick and dirty:

echo foo | perl -nlE'print if $t ||= m{bar} }{ exit 1 if !$t'

Explanation:

The "Eskimo kiss"™ }{ closes the while loop (which is implied by -n). In the if statement a varibable $t is 1 as soon as the first match happens.

Patrick J. S.

Posted 2014-12-04T04:12:37.527

Reputation: 113

0

If i was to solve the problem "quick & dirty" I would simply try something like this

echo foo | perl -nle' print if m{bar} or print 1'

Hope this was helpful.

Eamonn Travers

Posted 2014-12-04T04:12:37.527

Reputation: 496

1That prints "1", but doesn't exit with status 1/failure. – hpique – 2014-12-04T04:57:58.577

1

you can replace print 1 with die 1 (for failure; should abort script) or exit 1 (return status of 1, but don't throw error) if you want. http://perldoc.perl.org/functions/exit.html

– Frank Thomas – 2014-12-04T05:59:15.440

Hi. Like Frank said, die or exit will return 1 or failure. – Eamonn Travers – 2014-12-04T08:22:20.927