How can I convert a scalar containing a string with newlines in an array with those lines as elements?
For example, considering this:
$lines = "line 1\nline 2\nline 3\n";
I want to retrieve this:
$lines[0] --> "line 1\n"
$lines[1] --> "line 2\n"
$lines[2] --> "line 3\n"
Ideally, I'd like to keep the newline in the aray elements.
You can use a negative look-behind to preserve the newline in split:
@lines = split /(?<=\n)/, $lines;
One way is to use split
then map
.
use warnings;
use strict;
my $lines = "line 1\nline 2\nline 3\n";
my @lines = map { "$_\n" } split /\n/, $lines;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With