Perl String Gotcha’s Moments

This post is about a few Gotcha moments I encounted this morning when playing around with a super basic Perl script.

My first gotcha moment was trying work with a string from standard input. I wanted to just print the incoming string to standard out unless the incoming string contained ‘exit’. Here is my first attempt.

#!/usr/bin/perl
$lvc = 1;
until ( $lvc eq 0 ) {
    $line = <STDIN>;
	if($line eq 'exit'){
		print 'Now closing the loop';
		$lvc = 0;
	}
	else{
		print $line;
	}	
}

exit 0;

What’s wrong with that?
Well, the code in the if statement will never exit, even if you type exit. Getting strings from standard input will add a newline character, “\n”, onto the string.

How to fix this?
The approach I tried was use chomp(). Chomp() seems to remove the last “element” (Really bad description) of a string. In my case, my next attempt using chomp made the logic work.

#!/usr/bin/perl
$lvc = 1;

until ( $lvc eq 0 ) {
    chomp($line = <STDIN>);
    if($line eq 'exit'){
	print 'Now closing the loop';
	$lvc = 0;
    } else {
	print $line;
    }	
}

exit 0;

Is everything good now?
Nope, well kinda. Let’s say I type in “Hello”, the string hello will be echoed to standard out, but the terminal cursor will still be after the echoed hello. To fix this I tried cat a newline onto the printed $line.

#!/usr/bin/perl
$lvc = 1;

until ( $lvc eq 0 ) {
    chomp($line = <STDIN>);
    if($line eq 'exit'){
	print 'Now closing the loop';
	$lvc = 0;
    } else{
	print $line.'\n';
    }	
}

exit 0;

We’re good now right?
Nope, this script will literal print out ‘\n’ after your echoed input. Which leads my second gotcha moment. Double quotes mater. Turns out Perl is picking when it comes to string literals. Using ‘\n’ will be viewed as a normal string by the Perl compiler, you have to wrap the new line character around with double quotes. This final iteration of the script will work the way I intended it to.

#!/usr/bin/perl
$lvc = 1;

 until ( $lvc eq 0 ) {
    chomp($line = <STDIN>);  #Standard Input
	if($line eq 'exit'){
		print 'Now closing the loop';
		$lvc = 0;
	}
	else{
		print $line."\n";
	}	
}
exit 0;

# Sample Input: 'Hello'
# Given Output: 'Hello'

# Sample Input: 'exit'
# Given Output: 'Now closing the loop'
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s