Your specific problem (things being printed in the wrong order) appears to be due to the combination of double quotes and the x modifier. The double quotes in my $searchPattern = "(^\#!/usr/bin/perl.*?\n)"; causes "\#" to be inserted in the string as plain "#". The x modifier causes Perl to read "#" as the start of a comment. Thus the regex ends up being ^ alone followed by a comment whose text is "!/usr/bin/perl". The net effect is that $1 evaluates to the empty string. The regular expression matches the position at the start of the string and so inserts $insertion at the start of the string. /usr/bin/perl is never matched.

Now for how to avoid such problems in the future:

And a few comments on best practice:

The following code illustrates these points and outputs the insertion code in the correct position:

#!/usr/bin/perl -w ###-DDEBUGGING -d -Dslt` use strict; use warnings; use Env; use English qw( no_match_vars ); my $searchPattern='(^\#!/usr/bin/perl[^\n]*\n)'; my $insertion = "\nuse English \( no_match_vars \);\n"; my $content = "#!/usr/bin/perl \n\nyaba-dubba-doo\n"; print "content = <$content>\n"; print "insertion = <$insertion>\n"; $content =~ s?$searchPattern?${1}${insertion}?msx; print "content now = <$content>"; exit 0;

which outputs

content = <#!/usr/bin/perl yaba-dubba-doo > insertion = < use English ( no_match_vars ); > content now =<#!/usr/bin/perl use English ( no_match_vars ); yaba-dubba-doo >

Best, beth

Updated: explain specific cause of error and added code sample.


In reply to Re: junior application developer by ELISHEVA
in thread code file refactoring to use English module as per PBP by lloder174

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.