How to Replace white space in perl

44,212

Solution 1

Your first code will take a newline off the end of $myString if it exists and then remove all "/" characters. The second line of code will remove all whitespace characters. Is there a typo?

Maybe you want to know you can replace this:

chomp($myString);
$myString =~ s/\s//g;

with this:

$myString =~ s/\s//g;

If that's the question, then yes. Since a newline counts as whitespace, the second code example do the job of both lines above.

Solution 2

From perldoc chomp:

chomp remove the newline from the end of an input record when you're worried that the final record may be missing its newline.

When in paragraph mode ($/ = "" ), it removes all trailing newlines from the string. When in slurp mode ($/ = undef ) or fixed-length record mode ($/ is a reference to an integer or the like, see perlvar) chomp() won't remove anything.

you can remove leading and trailing whitespace from strings like,

$string =~ s{^\s+|\s+$}{}g
Share:
44,212
DarRay
Author by

DarRay

Love to solve puzzles.. and music too.

Updated on March 08, 2020

Comments

  • DarRay
    DarRay about 4 years
    chomp($myString);
    $myString =~ s/\///g;
    

    can i replace those two with

    $myString =~ s/\s//g;
    

    are there any difference? Please explain.