Reputation: 63
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.
Upvotes: 6
Views: 2249
Reputation: 61937
Another way, without split
:
use warnings;
use strict;
my $lines = "line 1\nline 2\nline 3\n";
my @lines = $lines =~ /(.*\n)/g;
Upvotes: 3
Reputation: 56457
Use split
:
my @lines = split(/\n/m, $lines);
EDIT: to keep the newlines, split on /^/m
as mentioned in the comments, or use a zero-width look-behind, as mentioned in another answer.
Upvotes: 2
Reputation: 67900
You can use a negative look-behind to preserve the newline in split:
@lines = split /(?<=\n)/, $lines;
Upvotes: 7
Reputation: 61937
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;
Upvotes: 4