Perl 在文字字符上拆分字符串 \n

Perl split string on literal character \n

我有一个文件是从上游系统传来的。它包含一个非常大的字符串,并且包含一个文字 \n。我需要在文字 \n.

上拆分那个大字符串

这是我正在获取的文件:

one\nsometing\ntwo\nthree\nmore things\nsome more things

正如我上面提到的,我需要在文字 \n 上拆分这个大字符串,预期输出如下:

one
something
two
three
more things
some more things

您可以像使用其他任何东西一样使用 split

@x = 'one\nsometing\ntwo\nthree\nmore things\nsome more things';

@split_x = split /\n/, $x;

然后就可以拆分打印了:

print join "\n", @split_x;

甚至作为一个班轮

print join "\n", split /\n/, $x;

如果您的字符串包含 \ + n 这两个字符而不是换行符,您需要在使用 split 时“转义”\,因此 \ 变成 \.

示例:

#!/bin/perl

my $str='one\nsometing\ntwo\nthree\nmore things\nsome more things';

my @splitted = split/\n/, $str;    # split on the two characters '\' + 'n'

print join("\n", @splitted) . "\n";