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

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


Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |