Remove whitespace in Perl

Home > Search
  by

Variable

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

#!/usr/bin/perl

my $foo = "  Hello    \n    World  \n";

@strings = split /\n/, $foo;

foreach $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 $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
       Hello
    World

 

The map function can be used to eliminate white space to the left of text in an array, so that all of the text is left justified.

map { s|^\s+|| } @greeting;

 

The following can be used to eliminate white space to the left of text in an variable, so that all of the text is left justified.

$greeting =~ s|^\s+||;

 

The result will be:

Hello
World
Hello
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 in the box below so that we can be sure you are a human.




Comments