Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace returns with spaces and commas with semicolons?

Tags:

perl

I want to be able to be able to replace all of the line returns (\n's) in a single string (not an entire file, just one string in the program) with spaces and all commas in the same string with semicolons.

Here is my code:

    $str =~ s/"\n"/" "/g;
    $str =~ s/","/";"/g;
like image 756
Padawan Avatar asked Dec 29 '25 17:12

Padawan


2 Answers

This will do it. You don't need to use quotations around them.

$str =~ s/\n/ /g;
$str =~ s/,/;/g;

Explanation of modifier options for the Substitution Operator (s///)

e       Forces Perl to evaluate the replacement pattern as an expression. 
g       Replaces all occurrences of the pattern in the string. 
i       Ignores the case of characters in the string. 
m       Treats the string as multiple lines. 
o       Compiles the pattern only once. 
s       Treats the string as a single line. 
x       Lets you use extended regular expressions. 
like image 102
hwnd Avatar answered Jan 01 '26 09:01

hwnd


You don't need to quote in your search and replace, only to represent a space in your first example (or you could just do / / too).

$str =~ s/\n/" "/g;
$str =~ s/,/;/g;
like image 24
squiguy Avatar answered Jan 01 '26 09:01

squiguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!