user3548698
user3548698

Reputation: 1

how to replace double quotes inside the string in perl

want to replace the apostrophes into double quotes in perl

Example

'It's raining'

Print

'It"s raining'

Upvotes: 0

Views: 15070

Answers (2)

youngthing
youngthing

Reputation: 384

You can use global search and replace, e.g.

 $your_string =~ s/'/"/g;

It's a lot simpler than any function call and gives access to other great bits of perl!

Adding the g at the end gives global search and replace, so all instances of ' within $your_string will be replaced and not just the first one.

Upvotes: 1

David W.
David W.

Reputation: 107040

You can use a backslash to quote the quote:

print "I think \"it's raining\" if you know what I mean\n";

However, a better way is to get use to using the quote-like operators qq( ... ) for double quotes and q( .. ) for single quotes:

print qq(I think "it's raining" if you know what I mean\n);

The parentheses can be almost any character, just like the substitution or regular expression match:

print qq/I think "it's raining" if you know what I mean\n/;
print qq#I think "it's raining" if you know what I mean\n#;

The nice thing about parentheses is that they must match:

print qq(I think "it's raining" if you know what I mean (he said with a wink)\n);

That still works.


Now the correct answer

I am using the Syntax str_replace( string_expr1, string_expr2, string_expr3 ) – user3548698

So, you're not escaping, you're replacing:

Use the s/.../.../ operator:

my $string = "it's raining";
my $string =~ s/'/"/g;   # The `g` means all instances
print "$string\n";       # Prints it"s raining.

Upvotes: 1

Related Questions