Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all . from string except the last?

Tags:

perl

I would like to remove all . from a string except from the last.

It can be done in JavaScript like so

var s='1.2.3.4';
s=s.split('.');
s.splice(s.length-1,0,'.');
s.join('');

but when try the same in Perl

my @parts = split /./, $s;
my @a = splice @parts, $#parts-1,0;
$s = join "", @a;

I get

Modification of non-creatable array value attempted, subscript -2 at ./test.pl line 15.

Question

Can anyone figure out how to do this in Perl?

like image 376
Sandra Schlichting Avatar asked Mar 19 '12 13:03

Sandra Schlichting


1 Answers

I would use a regexp with positive look-ahead in perl for the task:

perl -pe 's/\.(?=.*\.)//g' <<<"1.2.3.4"

Result:

123.4

EDIT to add a fix to your solution using split:

use warnings;
use strict;

my $s = '1.2.3.4';
my @parts = split /\./, $s; 
$s = join( "", @parts[0 .. $#parts-1] ) . '.' . $parts[$#parts];
printf "$s\n";
like image 179
Birei Avatar answered Nov 15 '22 07:11

Birei