How to delete everything. from a string except the last?

I would like to remove everything .from the row except the last one.

This can be done in JavaScript, for example:

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

but when you try to do 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?

+5
source share
7 answers

I would use regex with a positive look ahead in perlfor the task:

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

Result:

123.4

EDIT to add a fix to your solution with 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";
+8
source

First of all, remove the point in the split command: my @parts = split /\./, $s;

+4
source

split /./, . wild card. , :

... split /\./, $s;

splice ARRAY EXPR, OFFSET, LENGTH, LIST (perl v5.14). LENGTH 0, , .

, , , , , , , - :

my @parts = split /\./, $s;
my $end   = pop @parts;
$s        = join "", @parts, ".$end";

, ,

my @parts = split /\./, $s;
my $limit = @parts - 1;  # the field count for split
$s        = join "", split /\./, $s, $limit;

, , , , , LIMIT.

+4

, use diagnostics;

$ perl -Mdiagnostics -le " splice @ARGV, -1 ,0 "
Modification of non-creatable array value attempted, subscript -1 at -e line 1 (#1)
    (F) You tried to make an array value spring into existence, and the
    subscript was probably negative, even counting from end of the array
    backwards.

Uncaught exception from user code:
        Modification of non-creatable array value attempted, subscript -1 at -e line 1.
 at -e line 1.

$ perl -Mdiagnostics -le " splice @ARGV, -1 ,0 " argv now not empty

, , , 0 ( )

$ perl -le " print for splice @ARGV, 0, $#ARGV-1 " a b c
a

. $# ARGV - , $# ARGV -1,

$ perl -le " print for splice @ARGV, 0, $#ARGV " a b c
a
b

, @ARGV,

$ perl -le " print for splice @ARGV, 0, @ARGV-1 " a b c
a
b

? , .

$ perl -le " print for splice @ARGV, 0, 10 "
+3

, Perl

my @parts = split /\./, $s;
$s = join('', splice(@parts, 0, -1)) . '.' . $parts[-1];
+1

'.' splice.

use strict;
use warnings;

my $s = '1.2.3.4';

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

The first argument splitis a regular expression. In regular expressions, " ." means "match any character" (with / s) or "match any character except LF" (without / s). You need to run away from it to match the literal " .".

my @parts = split(/\./, $s, -1);            # "-1" to handle "1.2.3.4."
splice(@parts, -1, 0, '.') if @parts > 2;   # "if" to handle "1234"
$s = join('', @parts);

Substitution could also do this:

$s =~ s/\.(?=.*\.)//sg;
0
source

All Articles