activedecay activedecay - 8 months ago 85
Perl Question

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>

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download