5

Why does this work:

$my_str=~s/://g;

But this does not:

$my_str=~s/:://g;

I have a string that looks something like this: ::this:is:my:string and I need to remove the :: but not touch the :.

6
  • 3
    What happens when you try it? Commented Aug 29, 2011 at 15:12
  • are you doing one after the other ? Commented Aug 29, 2011 at 15:14
  • 3
    It works for me. At least it does with a string that looks exactly like "::this:is:my:string". I have no idea what it will do with a string that looks "something like" that. If you want real answers, show real code. Commented Aug 29, 2011 at 15:15
  • 2
    Add use strict; use warnings; to the top of your script. If you can still run the script without warnings, post your code. Commented Aug 29, 2011 at 16:39
  • 1
    Oh you know what. This script was written by another guy in my department and he commented out use strict; and use warnings; This explains why I was so puzzled. Thanks! Commented Aug 29, 2011 at 18:34

3 Answers 3

14

Works fine for me:

$ echo "::this:is:my:string" | perl -ne "s/:://g; print;"
this:is:my:string
Sign up to request clarification or add additional context in comments.

Comments

7

Are you sure you don't have any typos in your code? And that this substitution is in fact the problem? The following program worked for me:

my $var = '::a:b:c::';
print "$var\n";
$var =~ s/:://g;
print "$var\n";

Output:

$ perl test.pl
::a:b:c::
a:b:c
$ 

Edit to add a couple suggestions:

  1. Print the variable immediately before and after the substitution.
  2. No immediately the problem at hand, but if you only need to remove the :: at the beginning of the string, you may want to add a ^ to the regex to indicate that.

Comments

3

There are two things I can think of that would cause $my_str =~ s/:://g; fail:

  1. $my_str doesn't contains what you say it contains.
  2. pos($my_str) is set.

To make sure $my_str contains what you think it does, you could use Data::Dumper, but make sure to do $Data::Dumper::Useqq = 1; before using Dumper.

But first, make sure you aren't doing something like

if ($my_str =~ /.../g) {
   ...
   $my_str =~ s/:://g;
   ...
}

if ($my_str =~ /.../g) is a common mistake, and it could cause this problem. (I don't know why since it doesn't even make sense conceptually.) If so, get rid of the g in the if condition.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.