Perl (Scripting) - whitespace (\s)

by
Jeremy Canfield |
Updated: July 01 2021
| Perl (Scripting) articles
Variable
Let's say you have a variable named $greeting that contains white space before and after text.
#!/usr/bin/perl
use strict;
use warnings;
my $foo = " Hello \n World \n";
@strings = split /\n/, $foo;
foreach my $line (@strings) {
print "'$line'\n";
}
Running this script will display the white space before and after the text.
' Hello '
' World '
The following can be used to eliminate white space to the left and right of text in an variable.
foreach my $line (@strings) {
$line =~ s|^\s+||; # Remove whitespace before text
$line =~ s|\s+$||; # Remove whitespace after text
print "'$line'\n";
}
The result will be:
'Hello'
'World'
Array
Let's say you have an array named @greeting or variable named $greeting, and when the array or variable is printed, there is random whitespace to the left of the text.
Hello World
Goodbye World
The map function can be used to eliminate white space from the beginning and end of the array.
map { s|^\s+|| } @greeting;
map { s|\s+$|| } @greeting;
The following should be returned.
Hello World
Goodbye World
Did you find this article helpful?
If so, consider buying me a coffee over at