在map中,tr运算符是否会影响原始数组?

时间:2016-06-30 11:49:35

标签: perl

我写了这样的代码,

    my (@Last,@Input);
@Input=qw(This is FOR Testing);
map{ tr/A-Z/a-z/;tr/a-z//cd;push @Last,$_;} @Input;
print "Original array ==>@Input<===\n";
print "Modified array ==>@Last<===\n";

一旦我执行了代码,我得到了这样的输出,

Original array ==>this is for testing<===
Modified array ==>this is for testing<===

tr运算符是否会影响原始数组?

2 个答案:

答案 0 :(得分:1)

tr///默认具有破坏性。

要保留原始字符串,您应使用/r修饰符。

来自perldoc perlop

  

如果存在/r(非破坏性)选项,则为新的副本   制作字符串并将其字符音译,此副本为   无论是否被修改,都会返回

答案 1 :(得分:1)

/r无法使用的旧版Perls中(在5.14中引入),常见的习惯用语是

my @Input = qw( This is FOR Testing );
my @Output = map {
    my $s = $_;        # Break the aliasing.
    $s =~ tr/A-Z/a-z/;
    $s =~ tr/a-z//cd;
    $s
} @Input;