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?
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With