我如何在 Perl 6 中缩短数组?
How do I shorten an array in Perl 6?
如何在 Perl 6 中切断数组或数组引用?
在 Perl 5 中,我可以这样做:
my $d = [0 .. 9];
$#$d = 4;
在 Perl 6 中,如果我尝试这样做,我会收到错误消息:
my $d = [0 .. 9];
$d.end = 4; # Cannot modify an immutable Int
这可行,但它看起来不如 Perl 5 方式漂亮,而且可能很昂贵:
$d.=splice(0, 5);
splice
is probably the best choice here, but you can also shorten to five elements using the ^N
range constructor shortcut (I call this the "up until" "operator" but I am sure there is a more correct name since it is a constructor of a Range
):
> my $d = [ 0 .. 9 ];
> $d.elems
> 10
> $d = [ $d[^5] ]
[0 1 2 3 4]
> $d.elems
5
> $d
[0 1 2 3 4]
"The caret is ... a prefix operator for constructing numeric ranges
starting from zero".
(From the Range
documentation)
有人可以说 perl6 是 "perl-ish",因为它通常具有某些操作的显式版本(使用一种 "predictable" 语法 - 方法、例程和 :adverb
, 等等),如果你不熟悉这门语言,这是可以理解的,然后是 shortcut-ish 变体。
我不确定哪种方法(splice
对比快捷方式对比使用 :delete
,正如 Brad Gilbert 提到的那样)在速度或内存使用方面具有优势。如果你 运行:
perl6 --profile -e 'my $d = [ 0 .. 9 ]; $d=[ $d[^5] ]'
perl6 --profile -e 'my $d = [ 0 .. 9 ]; $d.=splice(0, 5);'
你可以看出细微的差别。如果与真实的程序和工作负载进行比较,差异可能会更显着。
有一个简单的方法:
my $d = [0..9];
$d[5..*] :delete;
如果数组是无限数组,那就有问题了。
$d.splice(5)
也有同样的问题
你最好的选择可能是 $d = [ $d[^5] ]
在一般情况下你可能对数组一无所知,并且需要一个可变数组。
如果你不需要它是可变的$d = $d[^5]
returns 列表可能更好。
另一种选择是使用 xx
运算符:
my $d = [0..9];
$d.pop xx 4; #-> (9 8 7 6)
say $d; #-> [0 1 2 3 4 5]
$d = [0..9];
$d.shift xx 5 #-> (0 1 2 3 4)
say $d; #-> [5 6 7 8 9)
如何在 Perl 6 中切断数组或数组引用?
在 Perl 5 中,我可以这样做:
my $d = [0 .. 9];
$#$d = 4;
在 Perl 6 中,如果我尝试这样做,我会收到错误消息:
my $d = [0 .. 9];
$d.end = 4; # Cannot modify an immutable Int
这可行,但它看起来不如 Perl 5 方式漂亮,而且可能很昂贵:
$d.=splice(0, 5);
splice
is probably the best choice here, but you can also shorten to five elements using the ^N
range constructor shortcut (I call this the "up until" "operator" but I am sure there is a more correct name since it is a constructor of a Range
):
> my $d = [ 0 .. 9 ];
> $d.elems
> 10
> $d = [ $d[^5] ]
[0 1 2 3 4]
> $d.elems
5
> $d
[0 1 2 3 4]
"The caret is ... a prefix operator for constructing numeric ranges starting from zero".
(From theRange
documentation)
有人可以说 perl6 是 "perl-ish",因为它通常具有某些操作的显式版本(使用一种 "predictable" 语法 - 方法、例程和 :adverb
, 等等),如果你不熟悉这门语言,这是可以理解的,然后是 shortcut-ish 变体。
我不确定哪种方法(splice
对比快捷方式对比使用 :delete
,正如 Brad Gilbert 提到的那样)在速度或内存使用方面具有优势。如果你 运行:
perl6 --profile -e 'my $d = [ 0 .. 9 ]; $d=[ $d[^5] ]'
perl6 --profile -e 'my $d = [ 0 .. 9 ]; $d.=splice(0, 5);'
你可以看出细微的差别。如果与真实的程序和工作负载进行比较,差异可能会更显着。
有一个简单的方法:
my $d = [0..9];
$d[5..*] :delete;
如果数组是无限数组,那就有问题了。
$d.splice(5)
也有同样的问题
你最好的选择可能是 $d = [ $d[^5] ]
在一般情况下你可能对数组一无所知,并且需要一个可变数组。
如果你不需要它是可变的$d = $d[^5]
returns 列表可能更好。
另一种选择是使用 xx
运算符:
my $d = [0..9];
$d.pop xx 4; #-> (9 8 7 6)
say $d; #-> [0 1 2 3 4 5]
$d = [0..9];
$d.shift xx 5 #-> (0 1 2 3 4)
say $d; #-> [5 6 7 8 9)