Perl:如何在$ LIST_SEPARATOR($“)中使用命令行特殊字符(换行符,制表符) [英] Perl: How to use command line special characters (newline, tab) in $LIST_SEPARATOR ($")
问题描述
我想将变量的值(例如,由命令行选项固定)用作列表分隔符,使该值成为特殊字符(换行符,制表符等).
I would like to use the value of a variable (fixed by a command line option for instance) as a list separator, enabling that value to be a special character (newline, tabulation, etc.).
不幸的是,由于以下两个print语句的行为不同,因此朴素的方法行不通:
Unfortunately the naïve approach does not work due to the fact that the two following print statement behave differentely :
my @tab = ("a","b","c");
# block 1 gives expected result:
# a
# b
# c
{
local $" = "\n"; #" let us please the color syntax engine
print "@tab";
}
# block 2 gives unwanted result:
# a\nb\nc
{
use Getopt::Long;
my $s;
GetOptions('separator=s' => \$s);
local $" = "$s"; #" let us please the color syntax engine
print "@tab";
}
有什么主意我可以纠正第2块,以便得到所需的结果(由第1块产生的结果)?
Any idea I can correct the block 2 so that I get the wanted result (the one produced by block 1) ?
推荐答案
如果您分配相同的字符串,则它的工作原理实际上是相同的.Perl的
It actually does work the same if you assign the same string. Perl's
"\n"
创建一个由换行符组成的字符串.使用我的shell(bash),您将使用
creates a one character string consisting of a newline. With my shell (bash), you'd use
'
'
要做同样的事情.
$ perl a.pl --separator='
'
a
b
ca
b
c
您没有这样做.您将由两个字符 \
和 n
组成的字符串传递给Perl.
You didn't do this. You passed a string consisting of the two characters \
and n
to Perl instead.
如果您的程序将两个字符 \ n
转换为换行符,则需要告诉它这样做.
If you your program to convert two chars \n
into a newline, you'll need to tell it to do so.
my @tab = qw( a b c );
sub handle_escapes {
my ($s) = @_;
$s =~ s/\\([\\a-z])/
$1 eq '\\' ? '\\' :
$1 eq 'n' ? "\n" :
do { warn("Unrecognised escape \\$1"); "\\$1" }
/seg;
return $s;
}
{
my $s = '\n'; #" let us please the color syntax engine
local $" = handle_escapes($s);
print "@tab";
}
{
use Getopt::Long;
my $s;
GetOptions('separator=s' => \$s);
local $" = handle_escapes($s); #" let us please the color syntax engine
print "@tab";
}
$ perl a.pl --separator='\n'
a
b
ca
b
c
这篇关于Perl:如何在$ LIST_SEPARATOR($“)中使用命令行特殊字符(换行符,制表符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!