How to Clean Up the Start & End of a String in Perl

Perl does not have a built-in function that removes whitespace from the beginning or end of a string, but you can use the built-in substitution operator to perform the same function. The substitution operator uses standard regular expressions to replace a portion of a string with other characters. Removing whitespace can help clean up and validate user input, and you can also use it to remove unnecessary space in a text file.

Instructions

    • 1

      Open a blank plain text document.

    • 2

      Type the following lines to start the Perl script:

      #!bin/perl
      use strict;
      use warnings;

    • 3

      Type the following lines to create a string that contains whitespace at the beginning and the end of the string, and print the string to the screen:

      my $orig_string = " This is a string ... ";
      print $orig_string."\n";

    • 4

      Type the following lines to remove the whitespace from the beginning of the string and print the edited string to the screen:

      $orig_string =~ s/^\s+//;
      print $orig_string;

    • 5

      Type the following lines to remove the whitespace from the end of the string and print the edited string to the screen:

      $orig_string =~ s/\s+$//;
      print $orig_string."\n";

    • 6

      Save and close the file.

Tips & Warnings

  • Use the substitution operator to remove any specified characters from the beginning or end of a string.

Related Searches:

References

Resources

Comments

Related Ads

Featured