How to Remove a Carriage Return From a String in Perl
Write programs in the Practical Extraction and Report Language scripting language when you need a tool that can quickly automate string manipulation, provide user interaction and deliver acceptable formatting. Carriage returns tend to disrupt the formatting of user input and Perl program output so that text strings look messy and difficult to follow. Use the "chomp" keyword to remove carriage returns and clean up program input and output.
Things You'll Need
- Computer with the Perl programming language interpreter installed
- Perl script file containing the text string for which you want a carriage return removed
Instructions
-
-
1
Open a command line terminal window on a computer that has Perl enabled. Open the Perl script file containing a text string for which the carriage return must be removed.
-
2
Use the arrow keys on the keyboard to position the cursor immediately after the line in which a variable is assigned the text string as its value. For example, if you wish to remove the carriage return from the "Test" string below:
$myVariable = "Test\n";
Add a "chomp" function line for the text string variable immediately after the text string assignment as written below:
chomp($myVariable);
-
-
3
Use the arrow keys to position the cursor after a line that accepts user input and write a "chomp" function line for the text string input variable to remove the carriage return from user input to clean up formatting. For example:
while (user $input = <STDIN>) {
print "The user typed '$input'\n";
last if ($input eq '');
}
will include the carriage return with the user input when the user presses the "Enter" key. To remove the carriage return, insert the "chomp" function as written below:
while (user $input = <STDIN>) {
chomp($input);
print "The user typed '$input'\n";
last if ($input eq '');
}
-
1
References
- Photo Credit Thinkstock/Comstock/Getty Images