How do I convert a multiline string to array?
my $text= \" ads da
sda
s
da
d
as
das
d a as dasd
\\n
\";
Note : I dont want to re
You could split on the beginnings of the lines by using the ^
metacharacter and the m
regexp modifier (letting ^
match the beginning of the line instead of just the beginning of the string):
split /^/m, $text
Actually, you can leave out the m
since split
puts it in for you in this case. From perldoc -f split
: "A PATTERN of "/^/" is treated as if it were "/^/m", since it isn’t much use otherwise."
Using your value for $text
, this code:
use Data::Dumper;
$Data::Dumper::Useqq=1;
print Data::Dumper->Dump([[split /^/, $text]], ["*text"]);
Prints this:
@text = (
" ads da\n",
"sda\n",
"s \n",
"da\n",
"d\n",
"as\n",
"\n",
"das\n",
"d a as dasd\n",
"\n",
"\n",
"\n"
);
Keeping in mind that the first argument to split
is a pattern:
#!/usr/bin/perl
use strict; use warnings;
use YAML;
my $text = " ads da
sda
s
da
d
as
das
d a as dasd
\n
";
print Dump [ split /(\n)/, $text ];
Output:
--- - ' ads da' - "\n" - sda - "\n" - s - "\n" - da - "\n" - d - "\n" - as - "\n" - '' - "\n" - das - "\n" - d a as dasd - "\n" - '' - "\n" - '' - "\n" - '' - "\n"
I had fun putting this one together: Voila! Your string is now an array without split
-ting it:
use strict qw<subs vars>;
use warnings;
@{" ads da
sda
s
da
d
as
das
d a as dasd
\n
"} = 1..3
;
As it stands, the question could be worded more clearly.
my @text = split "\n", $text;
My sense is you are focusing on the wrong problem.
Instead of trying to convert a scalar multi-line string constant into a list, maybe your question should be "How do I have a multi-line string initiated into a Perl list or array?"
Look at Perl's List value constructors in Perldata.
Of particular applicability to your question is how to use a heredoc to initiate an array with a multi-line string:
#!/usr/bin/perl
use strict; use warnings;
use YAML;
my @text= <<END =~ m/(^.*\n)/mg;
ads da
sda
s
da
d
as
das
d a as dasd
\n
END
print Dump \@text;
Prints:
---
- " ads da\n"
- "sda\n"
- "s \n"
- "da\n"
- "d\n"
- "as\n"
- "\n"
- "das\n"
- "d a as dasd\n"
- "\n"
- "\n"
- "\n"
Use the idioms Luke!