将多行字符串转换为数组 [英] Converting multi-line string to array

查看:203
本文介绍了将多行字符串转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I convert a multiline string to array?

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

das
d a as dasd
\n

";

注意:我是否要删除或删除换行符?

推荐答案

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

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

实际上,您可以省去m,因为在这种情况下,split会代入它.来自perldoc -f split:将"/^/"的模式视为"/^/m",因为在其他情况下它用处不大."

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."

使用您的$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"
        );

这篇关于将多行字符串转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆