More Special Variables in Perl: Outputs

By Juliet Kemp (Send Email)
Posted Dec 7, 2009


After looking last week at at special Perl variables for reading things in, here are some that may be useful when you want to write things out.

Last week we looked at special Perl variables for reading things in; this week we look at the other side -- variables that are useful when you want to write things out.

$| If this is set to a non-zero value, it forces an immediate buffer flush, and then a flush after every write or print. The default is zero, which means some buffering is done. If you're writing to a file, you're not likely to be too worried about this, but if you're writing to a pipe or a socket, you may want to be sure your output doesn't wait around.

$, This variable sets what print outputs between the elements that are passed in to it. By default it's undefined. So, this code:

print "1", "2", "3", "n";
{
	local $, = " ";
	print "1", "2", "3", "n";
}
will output
123
1 2 3
(See last week's article for discussion of using local to keep your variable re-setting tidy.)

$" This variable sets what print outputs between the elements of an array that is passed into it surrounded with double quotes. By default it's space. So this code:

my @array = (1, 2, 3);
print "@array", "n";
{
	local $" = ":";
	print "@array", "n";
}
will output
1 2 3
1:2:3
$ This variable sets the value automatically added to the end of each print statement. By default, this is the empty string, but if you're fed up with always adding newline to your print statements (as with all my examples above!), you can reset it:
print "No newline here.";
{
	local $ = "n";
	print "Newline automatically added.";
}
These are just a few examples.There are many, many more Perl special variables out there to experiment with.

Juliet Kemp has been messing around with Linux systems, for financial reward and otherwise, for about a decade. She is also the author of "Linux System Administration Recipes: A Problem-Solution Approach" (Apress, 2009).

Follow ServerWatch on Twitter

Page 1 of 1

Tags: Linux, perl

Comment and Contribute

Your name/nickname

Your email

(Maximum characters: 1200). You have characters left.