user00011
user00011

Reputation: 123

Perl - Join Elements of array till a specified length

I have an array of strings say whose length can be anywhere from 1 to 20. I need to join the 1st 3 elements of array into a string. I used.

@a = ("Hello","world","welcome");
$b = join(":",@a[0..2])

This produces desired output Hello:World:welcome

But When the length of the array is less than 3 say @a = ("hello","wolrd")

I get Hello:world: as output. If I have 1 variable I get Hello:: as the output.

I want to restrict joining based on the array's length. Is there any way out to do this?

Upvotes: 2

Views: 761

Answers (3)

zdim
zdim

Reputation: 66954

Can also check the array size and join what you want, or the whole array

my $joined = join ':', (@ary > 3 ? @ary[0..2] : @ary);

Upvotes: 4

Grinnz
Grinnz

Reputation: 9231

With List::Util 1.50 or newer you get the head function which is nice for this sort of thing, as it will only return up to the number of elements in the list.

use strict;
use warnings;
use List::Util 1.50 'head';
my @array = ('hello', 'world');
my $joined = join ':', head 3, @array; # hello:world

The splice function can serve as a poor-man's head/tail, but it requires an array specifically and will remove the returned elements from that array.

use strict;
use warnings;
my @array = ('hello', 'world');
my $joined = join ':', splice @array, 0, 3; # hello:world
# @array is now empty

Upvotes: 5

simbabque
simbabque

Reputation: 54371

You need a grep to filter out values that are undef.

my $b = join(":", grep defined, @a[0..2]);

Note that this will allow values with the empty string q{}.

Upvotes: 1

Related Questions