user3483676
user3483676

Reputation: 177

replace comma to dot in perl array

Does anyone know how to replace commas with dots in an array in perl?

INPUT:

my @array = qw(6,2 5,2 4,2 3,2 2,2 1,2);

foreach (@array) {
print $_."\n";
}

EXPECTED OUTPUT:

6.2
5.2
4.2
3.2
2.2
1.2

Upvotes: 0

Views: 2883

Answers (3)

Borodin
Borodin

Reputation: 126742

You need

no warnings 'qw'

to be able to do this at all without Perl complaining. (You do have warnings enabled I hope?)

This will do what you need

use strict;
use warnings;
use 5.014;

no warnings 'qw';

my @array = map tr/,/./r, qw(6,2 5,2 4,2 3,2 2,2 1,2);

say for @array;

output

6.2
5.2
4.2
3.2
2.2
1.2

Update

If you have @array defined already and need to modify it, then you can write just

tr/,/./ for @array

Upvotes: 1

Zaid
Zaid

Reputation: 37146

One could use s///:

s/,/./g for @array;

But since there is nothing regex-y about the LHS of the substitution, tr/// is more purpose-built for the task:

tr/,/./ for @array;

Upvotes: 3

mpapec
mpapec

Reputation: 50657

You can try transliteration

foreach (@array) {
  tr/,/./;
  print $_, "\n";
}

Upvotes: 2

Related Questions