in reply to Removing multiple trailing comment lines from a string

It would be good to see some oof your data, to try to figure out what you're doing and why.

Just a couple of comments on some code details, although it might be that it would be better to change it overall.

Why would you need this:

$s =~ s/^[ \t]+//mg; # remove leading whitespace from each line $s =~ s/^\s+//; # remove leading whitespace
when the second line will do everything that the firstline is doing? (Same from trailing spaces).

Similarly, I don't see the reason to run the same pair of statements three times:

$s =~ s/^;.*\Z//m; chomp $s; $s =~ s/^;.*\Z//m; chomp $s; $s =~ s/^;.*\Z//m; chomp $s;
Once should be enough, no? And I doubt the chomp is useful here.

Replies are listed 'Best First'.
Re^2: Removing multiple trailing comment lines from a string
by eyepopslikeamosquito (Archbishop) on Dec 23, 2016 at 09:38 UTC

    Why would you need this:
    $s =~ s/^[ \t]+//mg; # remove leading whitespace from each line $s =~ s/^\s+//; # remove leading whitespace
    when the second line will do everything that the firstline is doing?
    Remember that $s is a multi-line string. So the regex mg modifier in the first regex above ensures that each line in the multi-line string has leading spaces and tabs removed from it.

    The second regex, OTOH, does not have any modifiers, so it does not apply to every line in the multi-line string; instead, it trims leading whitespace (this time, including newlines) from the front of the multiline string -- trimming multiple blank lines from the front of a multi-line string, for example.

Re^2: Removing multiple trailing comment lines from a string
by eyepopslikeamosquito (Archbishop) on Dec 23, 2016 at 09:53 UTC

    Similarly, I don't see the reason to run the same pair of statements three times:
    $s =~ s/^;.*\Z//m; chomp $s; $s =~ s/^;.*\Z//m; chomp $s; $s =~ s/^;.*\Z//m; chomp $s;
    Once should be enough, no? And I doubt the chomp is useful here.
    Again, remember we are dealing with a multi-line string. So running it once removes just the last comment line, not the last three comment lines. Also, please note that the first:
    $s =~ s/^;.*\Z//m;
    removes the contents of the last comment line of a multi-line string (note that \Z matches just the end of the (multi-line) string, not the end of each line). So if you ran it again without the chomp it would do nothing because you've have already removed the last comment line! The chomp is needed to remove the newline now sitting at the end of the string. An alternative to chomp, suggested above by tye, is to eschew the m modifier and remove the newline as part of the regex, like so:
    s/\n;.*\Z//