Broad Network


Trimming and Padding Strings in Perl

Handling Strings in Perl – Part 4

Perl Course

Foreword: In this part of the series I explain how to trim and pad a string in Perl.

By: Chrysanthus Date Published: 23 Oct 2015

Introduction

This is part 4 of my series, Handling Strings in Perl. In this part of the series I explain how to trim and pad a string in Perl. You should have read the previous parts of the series before reaching here, as this is a continuation.

Whitespace Characters
This is a list of whitespace characters:

        Sequence     Note      Description
        \t                 tab              (HT, TAB)
        \n                 newline         (NL)
        \r                 return            (CR)
        \f                 form feed         (FF)
        \b                 backspace         (BS)

Trimming All Whitespaces from Beginning
You can strip all the whitespaces from the beginning of a string. Use the substitution operator, where the replacement is nothing, that is:

    $string =~ s/^\s+//

Try the following code:

use strict;

    my $str = "\tspare part";
    print $str, "\n";

    $str =~ s/^\s+//;

    print $str;

The output is:

        spare part
spare part

Trimming All Whitespaces from the End
You can strip all the whitespaces from the end of a string. Use the substitution operator, where the replacement is nothing, that is:

    $string =~ s/\s+$//

Try the following code:

use strict;

    my $str = "spare part\n";
    print $str, "\n";

    $str =~ s/\s+$//;

    print $str;

The output is:

spare part

spare part
with no blank (new) line after the second print.

Trimming from Beginning and End
To do this, you can use both statements:

    $string =~ s/^\s+//
    $string =~ s/\s+$//

You can also use a combined statement as follows, but it will be slower than the separate statements.

    $string =~ s/^\s+|\s+$//g

Because of the g modifier, both the beginning and ending whitespaces will be stripped off.

Try the following code:

use strict;

    my $str = "\tspare part\n";
    print $str, "\n";

    $str =~ s/^\s+//;
    $str =~ s/\s+$//;

    print $str;

The output is:

        spare part

spare part

Padding a string with Blanks or Zeroes
You can left pad a string with spaces or zeroes. You can right pad a string with spaces. You pad a string to obtain a particular string length. You use the sprintf() function as in the following examples. In the examples, $pad_len is the new string length; and $text is the string needing padding.

The following code left pad a string with blanks:

use strict;

    my $text = "book";
    my $pad_len = 7;


    # Left padding a string with blanks (no truncation):
    my $padded = sprintf("%*s", $pad_len, $text);

    print $padded;

The output is:

“   book”

The following code right pad a string with blanks:

use strict;

    my $text = "book";
    my $pad_len = 7;


    # Right padding a string with blanks (no truncation):
    my $padded = sprintf("%-*s", $pad_len, $text);

    print $padded;

The output is:

“book   ”

The following code left pad a string with zeroes:

use strict;

    my $text = 25645;
    my $pad_len = 8;


    # Left padding a number with 0s  (no truncation):
    my $padded = sprintf("%0*d", $pad_len, $text);

    print $padded;

The output is:

    00025645

That is it for this part of the series. We stop here and continue in the next part.

Chrys

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

BACK NEXT

Comments

Become the Writer's Fan
Send the Writer a Message