How to remove and ID from a string

Viewed 470

I have a string that looks like this, they are ids in a table:

1,2,3,4,5,6,7,8,9

If someone deletes something from the database, I will need to update the string. I know that doing this it will remove the value, but not the commas. Any idea how can I check if the id has a comma before and after so my string doesn't break?

$new_values = $original_values[0];
$new_values =~ s/$car_id//;

Result: 1,2,,4,5,6,7,8,9 using the above sample (bad). It should be 1,2,4,5,6,7,8,9.

4 Answers

To remove the $car_id from the string:

my $car_id = 3;
my $new_values = q{1,2,3,4,5,6,7,8,9}; 
$new_values = join q{,}, grep { $_ != $car_id } 
    split /,/, $new_values; 
say $new_values;
# Prints:
# 1,2,4,5,6,7,8,9

If you already removed the id(s), and you need to remove the extra commas, reformat the string like so:

my $new_values = q{,,1,2,,4,5,6,7,8,9,,,}; 
$new_values = join q{,}, grep { /\d/ } split /,/, $new_values; 
say $new_values;
# Prints:
# 1,2,4,5,6,7,8,9
s/^\Q$car_id\E,|,\Q$car_id\E\b//

Another approach is to store an extra leading and trailing comma (,1,2,3,4,5,6,7,8,9,)

The main benefit is that it makes it easier to search for the id using SQL (since you can search for ,$car_id,). Same goes for editing it.

On the Perl side, you'd use

s/,\K\Q$car_id\E,//    # To remove
substr($_, 1, -1)      # To get actual string

You can use

s/^$car_id,|,$car_id\b//

Details

  • ^ - start of string
  • $car_id - variable value
  • , - comma
  • | - or
  • , - comma
  • $car_id - variable value
  • \b - word boundary.

Ugly way: use regex to remove the value, then simplify

$new_values = $oringa_value[0];
$new_values =~ s/$car_id//;
$new_values =~ s/,+/,/;

Nice way: split and merge

$new_values = $oringa_value[0];
my @values = split(/,/, $new_values);
my $index = 0;
$index++ until $values[$index] eq $car_id;
splice(@values, $index, 1);
$new_values = join(',', @values);
Related