user3164754
user3164754

Reputation: 215

Using join to add a , to the last element in an array in perl

I have a date array. I am trying to add commas to the elements of the array. I am using join. I need comma added to the last element. Here's my input - 2020 02 20 My output should be - 2020,02,20,

Here's my code

@date = join( ',',@date); or @date = join( map "$_,",@date );

Bit i can't get the comma on the last element. It would be really great if this can be acheived using only join.

Thanks in advance.

Upvotes: 1

Views: 827

Answers (4)

toolic
toolic

Reputation: 62227

To modify all elements of an array, map is an appropriate tool:

use warnings;
use strict;

my @date = qw(2020 02 20);
@date = map "$_,", @date;

use Data::Dumper;
print Dumper(\@date);

__END__

$VAR1 = [
          '2020,',
          '02,',
          '20,'
        ];

Upvotes: 3

ikegami
ikegami

Reputation: 386501

I am trying to add commas to the elements of the array.

$_ = "$_," for @date;

But if you're trying to create a string rather than modify the array, you can use the following:

my $date = join '', map "$_,", @date;

The above can be sped up using the following clever yet still readable approach:

my $date = join ',', @date, '';

Upvotes: 4

Beano
Beano

Reputation: 7861

To use the right function for the job - you should use map to change all the elements of the array, and the concatenate it all together with join

my $date = join('', map { "$_," } @date);

Upvotes: 5

Alnitak
Alnitak

Reputation: 339965

Try:

my $date = join(',', @date, '');

i.e. just tell join that there's an extra element.

NB: the output of join is a single scalar string, not another array, hence $date above.

Upvotes: 10

Related Questions