activedecay
activedecay

Reputation: 10877

Why is chomp not removing whitespace around my string?

I don't understand why perl chomp isn't removing the whitespace surrounding my string. I've even tried to call chomp twice, for example, using bash:

$ perl -e 'use 5.22.4; chomp(my $extra=" lol "); chomp($extra); say "<$extra>"'
< lol >

I really expected to get

<lol>

Upvotes: 1

Views: 1807

Answers (3)

Chandan Paranjape
Chandan Paranjape

Reputation: 33

$string=~s/^\s+|\s+$//g;

This would work well for any generic string where you want to remove beginning and ending spaces.

Upvotes: 0

user7818749
user7818749

Reputation:

To remove all whitespace:

$string =~ s/\s+//g;

Left trim:

$string =~ s/^\s+//;

Right Trim:

$string =~ s/\s+$//;

Left and Right trim:

$string =~ s/^\s+|\s+$//g

We can then also build trimming fucntions. This helps in much bigger scripts where you would not want to write the full replacement strings each time, we write them once, then use the function to do the work.

This simple function can be used in any script as trim($string);

sub trim {
    $_[0] =~ s/^\s+|\s+$//g;
 }

Similarly with a full strip of whitespace.

 sub full_strip {
    $_[0] =~ s/\s+//g;
 }

in a script:

use strict;
use warnings;
my $string = "  this is line with leading and trailing whitespaces  ";
my $string2 = "         another one of those lines ";

trim($string);
trim($string2);

print "$string\n";
print "$string2\n";

full_strip($string);
full_strip($string2);

print "$string\n";
print "$string2\n";


sub trim {
    $_[0] =~ s/^\s+|\s+$//g;
   }

sub full_strip {
    $_[0] =~ s/\s+//g;
   }

Upvotes: 4

amon
amon

Reputation: 57640

Chomp only removes the line ending (can be set with $/ variable) from the end of the string. It does not trim the string. Perl does not have a built-in trim function. I usually spell out two substitutions instead:

s/^\s+//, s/\s+$// for $string;

Further reading:

Upvotes: 8

Related Questions