3

I am trying to replace all occurences of carriage-return,new line with just new line but I can not.
Trying: my $new_string = $old_string =~ s/\r\n/\n/g
Gives an empty $new_sting.
This: my $new_string = $old_string =~ s/\r\n$/\n/g also does not work giving an empty string.
What am I messing up here?

0

3 Answers 3

5

The problem with your original attempt is that $old_string binds with the substitution operator (so it's that variable that will be modified), and then the return value of the substitution operator becomes the number of times it succeeded in matching. That match count is placed in $new_string If the match failed, an empty string is used to signify the zero count.

Your original attempt will work fine in more recent versions of Perl that support the /r modifier with only a slight modification:

my $new_string = $old_string =~ s/\r\n/\n/gr;

That modifier triggers a "non-destructive" mode for the substitution operator, and returns the modified string instead of a count. The /r modifier was introduced in Perl 5.14, and is described in perlop.

In older versions of Perl, parenthesis may be used to manipulate precedence:

( my $new_string = $old_string ) =~ s/\r\n/\n/g

This syntax evaluates my $new_string = $old_string first, and then uses $new_string to bind with the substitution.

Sign up to request clarification or add additional context in comments.

Comments

4

This

my $new_string = $old_string =~ s/\r\n/\n/g

returns the number of substitutions, and not the new string. To see the new string, just print $old_string after the substitution.


From perlop:

s/PATTERN/REPLACEMENT/msixpodualgcer

Searches a string for a pattern, and if found, replaces that pattern with the replacement text and returns the number of substitutions made. Otherwise it returns false (specifically, the empty string). If the /r (non-destructive) option is used then it runs the substitution on a copy of the string and instead of returning the number of substitutions, it returns the copy whether or not a substitution occurred. The original string is never changed when /r is used. The copy will always be a plain string, even if the input is an object or a tied variable.

2 Comments

But when I print the $new_string I don't see 0. I see nothing
Because when there are no matches the $new_string returns nothing!
2

You're substituting on $old_string and $new_string contain only how many substitutions was done, so use parentheses to change precedence of operations,

(my $new_string = $old_string) =~ s/\r\n/\n/g;

2 Comments

How is that different from what I did?
@Jim precedence is different

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.