in reply to Re^2: Removing empty line(s) with regex in a multiple strings in a variable
in thread Removing empty line(s) with regex in a multiple strings in a variable

$str =~ s/(^|\n)[\n\s]*/$1/g;
Would it be possible to ask if it can be broken down step by step.

Here's one way to look at this regex: The replacement part is $1, so that means that whatever is matched by the first capture group (^|\n) is kept, while everything else ([\n\s]*) is removed. (^|\n) matches either: (1) ^ means to match at the beginning of the string, so any newlines or whitespace [\n\s]* at the beginning of the string are removed, or (2) \n, which means that any newlines or whitespace [\n\s]* after that newline character are removed, but the first newline character is kept. This is how empty lines, which are usually just a sequence of two newline characters \n\n, are changed into a single newline character, meaning the empty line(s) are removed.

If you're unsure of any of these things, then I can recommend perlretut.

Replies are listed 'Best First'.
Re^4: Removing empty line(s) with regex in a multiple strings in a variable
by JD (Novice) on Feb 11, 2019 at 09:35 UTC
    Thank you both very much. Will crack on with the tutorials and documentation right now!