Asuka Asuka - 1 year ago 87
Perl Question

perl $ anchor failed to match end of line


my $pattern = "mkdir a &"

As you can see, my patterns are commands and I want to do a pattern match for "&+EOL" to distinguish whether this command runs on background or not.

I tried with
but failed.

What is wrong? What is your suggestion with this pattern match?

45: if ($command =~ /&$/) {

DB<2> p $command

mkdir a &

DB<3> s

54: print $_;print "\n";

Answer Source

Your pattern works fine

use strict;
use warnings 'all';
use feature 'say';

my $pattern = 'mkdir a &';

say $pattern =~ /&$/ ? 'match' : 'no match';



It is impossible to tell from your question, but it is likely that you have some whitespace at the end of the string you are trying to match. Perhaps you have a space or a linefeed there, or perhaps you are processing a file that has originated on Windows and you have removed only the LF, leaving a terminating CR.

You can fix this by adding optional whitespace at the end of your regex pattern, like this

say $pattern =~ /&\s*$/ ? 'match' : 'no match';

You can see exactly what your string contains using Data::Dumper, like this

use Data::Dumper;
$Data::Dumper::Useqq = 1;

print Dumper $pattern;

In this instance it produces $VAR1 = "mkdir a &";, and you will be able to see if there are any superfluous characters after the &.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download