Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scalar with lines to array

Tags:

arrays

perl

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.

like image 709
new_user Avatar asked Aug 14 '11 18:08

new_user


2 Answers

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

@lines = split /(?<=\n)/, $lines;
like image 119
TLP Avatar answered Sep 23 '22 15:09

TLP


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;
like image 43
toolic Avatar answered Sep 22 '22 15:09

toolic