在Perl中,如何用零填充数组?我知道我可以得到数组的长度,然后用推送做一个for循环,但是有更可口的方式吗?
例如:
my @array = pad_with_zeroes("foo","bar","baz",6); # @array now eq ("foo",0)
(例如)List :: Util或类似的通用模块中是否还有可以执行此操作的内容?
解决方法
my @array = ("foo","baz"); my $total_length = 6; push @array,(0) x ($total_length - @array);
从perldoc开始:
Binary “x” is the repetition operator. In scalar context or if the left operand is not enclosed in parentheses,it returns a string consisting of the left operand repeated the number of times specified by the right operand. In list context,if the left operand is enclosed in parentheses or is a list formed by qw/STRING/,it repeats the list. If the right operand is zero or negative,it returns an empty string or an empty list,depending on the context.
作为具有指定用途的子:
sub pad_with_zeroes { my $n = pop; return ( @_,(0) x ($n-@_) ) }