加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 23:20:40 所属栏目:大数据 来源:网络整理
导读:在Perl中,如何用零填充数组?我知道我可以得到数组的长度,然后用推送做一个for循环,但是有更可口的方式吗? 例如: my @array = pad_with_zeroes("foo","bar","baz",6);# @array now eq ("foo",0) (例如)List :: Util或类似的通用模块中是否还有可以执行此操
在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-@_) ) }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读