在Perl中,如何用零填充数组?

前端之家收集整理的这篇文章主要介绍了在Perl中,如何用零填充数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在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-@_) ) }

猜你在找的Perl相关文章