Sorry, but the code shown is not removing newlines, as is easily demonstrated:

18:23 >perl -wE "my $s = qq[abc\n\t \ndef\n \ngh]; $s =~ s/^\s*$/X/m +g; say $s;" abc X def X gh 18:24 >

That’s because the /m modifier lets ^ and $ match at the beginning and end of each line within the string (see perlre#Modifiers). What the code does is to remove any whitespace from an otherwise empty line, i.e. whitespace is removed if and only if the whitespace is the only thing between two newlines (or between the beginning of the string and the first newline, or between the last newline and the end of the string). Is this what was intended? Or were you wanting to remove all whitespace except newlines themselves? If the latter, Laurent_R’s approach is what you want:

18:24 >perl -wE "my $s = qq[abc\n\t \nd\tef\n \ngh]; $s =~ s/[ \t]+/ +X/mg; say $s;" abc X dXef X gh 18:39 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re: regex doubt on excluding by Athanasius
in thread regex doubt on excluding by Anonymous Monk

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.