如何在 perl 中向数组添加空格?
How to add spaces to an array in perl?
该程序接受任意数量的命令行参数(大于 2 个)并将它们排序为 [a-z] 或 [z-a]。
sort.pl apple mike zebra
但是当我打印数组 @ARGV
时,结果显示为
applemikezebra
谢谢
试试这个:
print join (" ", @ARGV );
有几种可能的方法:
您可以使用join
。
print join ' ', sort @ARGV;
您可以使用 Perl 的特殊变量。
一个。 $,
插入在 print
的参数之间(默认为空)。
{ local $, = ' ';
print sort @ARGV;
}
b。 $"
在插入双引号时分隔数组成员(默认为 space)。
my @sorted = sort @ARGV;
{ local $" = ' ';
print "@sorted";
}
perlop 手册页 (perldoc perlop) 的 "Quote and Quote-like Operators" 部分指出:
Interpolating an array or slice interpolates the elements in order,
separated by the value of $" , so is equivalent to interpolating join
$", @array . "Punctuation" arrays such as @* are usually interpolated
only if the name is enclosed in braces @{*}, but the arrays @_ , @+ ,
and @- are interpolated even without braces.
For double-quoted strings, the quoting from \Q is applied after
interpolation and escapes are processed.
因此,打印以空格分隔的数组元素的一种方法是:
$ perl -le 'print "@ARGV"' apple mike zebra
apple mike zebra
举例说明$"变量的作用:
$ perl -le '$" = "|"; print "@ARGV"' apple mike zebra
apple|mike|zebra
该程序接受任意数量的命令行参数(大于 2 个)并将它们排序为 [a-z] 或 [z-a]。
sort.pl apple mike zebra
但是当我打印数组 @ARGV
时,结果显示为
applemikezebra
谢谢
试试这个:
print join (" ", @ARGV );
有几种可能的方法:
您可以使用
join
。print join ' ', sort @ARGV;
您可以使用 Perl 的特殊变量。
一个。
$,
插入在print
的参数之间(默认为空)。{ local $, = ' '; print sort @ARGV; }
b。
$"
在插入双引号时分隔数组成员(默认为 space)。my @sorted = sort @ARGV; { local $" = ' '; print "@sorted"; }
perlop 手册页 (perldoc perlop) 的 "Quote and Quote-like Operators" 部分指出:
Interpolating an array or slice interpolates the elements in order, separated by the value of $" , so is equivalent to interpolating join $", @array . "Punctuation" arrays such as @* are usually interpolated only if the name is enclosed in braces @{*}, but the arrays @_ , @+ , and @- are interpolated even without braces.
For double-quoted strings, the quoting from \Q is applied after interpolation and escapes are processed.
因此,打印以空格分隔的数组元素的一种方法是:
$ perl -le 'print "@ARGV"' apple mike zebra
apple mike zebra
举例说明$"变量的作用:
$ perl -le '$" = "|"; print "@ARGV"' apple mike zebra
apple|mike|zebra