Bootstrap FreeKB - Perl (Scripting) - whitespace (\s)
Perl (Scripting) - whitespace (\s)

Updated:   |  Perl (Scripting) articles


Let's say you have a variable named $greeting that contains white space before and after text.

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:




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 Buy Me A Coffee


Add a Comment

Please enter c13a83 in the box below so that we can be sure you are a human.