Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how can I pad an array with zeroes?

Tags:

perl

pad

In Perl, how can I pad an array with zeroes? I know that I can get the length of the array, and then do a for loop with a push, but is there a more palatable way?

For example:

my @array = pad_with_zeroes("foo", "bar", "baz", 6);

# @array now eq ("foo", "bar", "baz", 0, 0, 0)

Is there anything in (for example) List::Util or a similar common module that can do this, as well?

like image 797
Cerian Avatar asked Jan 11 '23 21:01

Cerian


1 Answers

my @array = ("foo", "bar", "baz");
my $total_length = 6;

push @array, (0) x ($total_length - @array);

From 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.

As a sub with the specified usage:

sub pad_with_zeroes { my $n = pop; return ( @_, (0) x ($n-@_) ) }
like image 183
mpapec Avatar answered Jan 25 '23 10:01

mpapec