new_user
new_user

Reputation: 63

Scalar with lines to array

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

Answers (4)

toolic
toolic

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

Jordão
Jordão

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

TLP
TLP

Reputation: 67900

You can use a negative look-behind to preserve the newline in split:

@lines = split /(?<=\n)/, $lines;

Upvotes: 7

toolic
toolic

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

Related Questions