将多行字符串转换为数组

时间:2010-11-19 14:41:10

标签: perl

如何将多行字符串转换为数组?

my $text= " ads da
sda
s 
da
d
as

das
d a as dasd
\n

";

注意:我不想删除或删除换行符?

5 个答案:

答案 0 :(得分:20)

目前的问题可能更明确。

my @text = split "\n", $text;

答案 1 :(得分:13)

您可以使用^元字符和m regexp修饰符(让^匹配行的开头而不仅仅是行的开头)在行的开头拆分字符串):

split /^/m, $text

实际上,在这种情况下,您可以省略m,因为split会为您提供。来自perldoc -f split:“”/ ^ /“的模式被视为”/ ^ / m“,因为它没有多大用处。”

使用$text的值,此代码:

use Data::Dumper;
$Data::Dumper::Useqq=1;
print Data::Dumper->Dump([[split /^/, $text]], ["*text"]);

打印出来:

@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"
        );

答案 2 :(得分:2)

请记住,split的第一个参数是一种模式:

#!/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 ];

输出:

---
- ' ads da'
- "\n"
- sda
- "\n"
- s
- "\n"
- da
- "\n"
- d
- "\n"
- as
- "\n"
- ''
- "\n"
- das
- "\n"
- d a as dasd
- "\n"
- ''
- "\n"
- ''
- "\n"
- ''
- "\n"

答案 3 :(得分:1)

我的感觉是你专注于错误的问题。

不是试图将标量多行字符串常量转换为列表,也许您的问题应该是“我如何将多行字符串启动到Perl列表或数组中?”

查看List value constructors中的Perl Perldata

对您的问题的特殊适用性是如何使用heredoc来启动具有多行字符串的数组:

#!/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;

打印:

---
- " ads da\n"
- "sda\n"
- "s \n"
- "da\n"
- "d\n"
- "as\n"
- "\n"
- "das\n"
- "d a as dasd\n"
- "\n"
- "\n"
- "\n"

使用成语Luke!

答案 4 :(得分:1)

我很乐意把这个放在一起: Voila!你的字符串现在是一个数组而没有 split - ting 它:

use strict qw<subs vars>;
use warnings;

@{" ads da
sda
s 
da
d
as

das
d a as dasd
\n
"} = 1..3
;