简体   繁体   English

使用Perl拆分数组

[英]Splitting array using perl

This is my array buff and I have stored the contents of the array as follows: 这是我的数组buff,我将数组的内容存储如下:

$buff[0]="3\nHi how are u I am f";
$buff[1]="ine\n The world is so";
$buff[2]="beautiful.\n";
$buff[3]="I love it.";

I want to split the array and print as 我想拆分数组并打印为

3
Hi how are u I am fine
The world is so beautiful.
I love it.

How do I accomplish this? 我该如何完成? I tried using split function like this: 我尝试使用像这样的split功能:

my @split_buff=split('\n', @buff);

foreach my $val (@split_buff) {
     print $val;
}

But I am not able to split with \\n as the delimiter, and I need to retain the delimiter as well. 但是我不能使用\\n作为分隔符来拆分,因此我也需要保留分隔符。 What's wrong in the code? 代码有什么问题?

我认为您可以简单地print它。

print @buff;

Join all together and split by \\n\\s* 一起加入并按\\n\\s*分割

my @split_buff = split /\n\s*/, join "", @buff;

foreach my $val (@split_buff) {

  print "$val\n";
}

I like answer: "print @buff;". 我喜欢回答:“ print @buff;”。 You can also try this code: 您也可以尝试以下代码:

    $text = ""; # or my $text;
    foreach $line (@buff) { $text = $text . "$line"; }
    print $text;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM