simon2016 has asked for the wisdom of the Perl Monks concerning the following question:

why my code below could not yield a match in the following line:

--tail read as this:

 .D(next_out_en), .CP(n16), .CDN(n48), .Q(

my code

 if ($tail =~ /^\s*(.+)\s+\.\s*CP\s*\(\s*(\S+)\s*\)\s*\,\s+(.+)\s*\n/i)

Replies are listed 'Best First'.
Re: pattern matching
by GrandFather (Saint) on Nov 07, 2016 at 23:14 UTC
    #!/usr/bin/perl use strict; use warnings; my $tail = ".D(next_out_en), .CP(n16), .CDN(n48), .Q(\n"; print "Matched: \$1 '$1', \$2: '$2', \$3: '$3'\n" if $tail =~ /^\s*(.+)\s+\.\s*CP\s*\(\s*(\S+)\s*\)\s*\,\s+(.+)\s*\n +/i;

    Prints:

    Matched: $1 '.D(next_out_en),', $2: 'n16', $3: '.CDN(n48), .Q('

    How is your code different? Maybe you don't have a newline at the end of $tail?

    Premature optimization is the root of all job security
Re: pattern matching
by toolic (Bishop) on Nov 07, 2016 at 21:43 UTC
Re: please help
by tybalt89 (Monsignor) on Nov 07, 2016 at 23:25 UTC

    Perhaps because $tail does not have a \n at the end?

Re: pattern matching
by hippo (Archbishop) on Nov 08, 2016 at 10:01 UTC
Re: pattern matching
by Marshall (Canon) on Nov 09, 2016 at 02:06 UTC
    The comments so far have to do with whether or not there is a "\n" at the end of tail.
    Here are some ways to make your regex insensitive to that:
    #!/usr/bin/perl use strict; use warnings; # modified code from [Grandfather] my $tail = ".D(next_out_en), .CP(n16), .CDN(n48), .Q(\n"; my $tail2 = ".D(next_out_en), .CP(n16), .CDN(n48), .Q("; print "MatchedA: \$1 '$1', \$2: '$2', \$3: '$3'\n" if $tail =~ /^\s*(.+)\s+\.\s*CP\s*\(\s*(\S+)\s*\)\s*\,\s+(.+)\s*$/ +i; print "MatchedB: \$1 '$1', \$2: '$2', \$3: '$3'\n" if $tail2 =~ /^\s*(.+)\s+\.\s*CP\s*\(\s*(\S+)\s*\)\s*\,\s+(.+)\s*$ +/i; print "MatchedC: \$1 '$1', \$2: '$2', \$3: '$3'\n" if $tail =~ /^\s*(.+)\s+\.\s*CP\s*\(\s*(\S+)\s*\)\s*\,\s+(.+)\s*/i +; __END__ Prints: MatchedA: $1 '.D(next_out_en),', $2: 'n16', $3: '.CDN(n48), .Q(' MatchedB: $1 '.D(next_out_en),', $2: 'n16', $3: '.CDN(n48), .Q(' MatchedC: $1 '.D(next_out_en),', $2: 'n16', $3: '.CDN(n48), .Q('
    First, notice that the $ anchor in a regex will ignore the line ending if it even exists.

    Second, notice that since "\n" is one of the white space characters. You can simply remove "\n" from the regex and it won't matter whether the "\n" character(s)are there or not. This is shown as option C.