Understanding Perl's Special Variables - ...And Output (Page 4 of 11 )
The reverse of the input record separator is the output record separator,
quite logically found in the $\ variable. While the $/ variable deals with
the delimiter used by Perl to break input into discrete records, the $\
variable controls which delimiter Perl uses to separate multiple print()
invocations.
By default, the output record separator is null, which means that the
output from every call to print() gets attached to the output from the
previous call. Consider the following example, which demonstrates:
#!/usr/bin/perl
# print output
print "The";
print "cow";
print "jumped";
print "over";
print "the";
print "moon";
Here's the output:
Thecowjumpedoverthemoon
You can alter this by specifying a different value from the $\ variable -
as the following example does:
#!/usr/bin/perl
# set output record separator
$\ = " -?- ";
# print output
print "The";
print "cow";
print "jumped";
print "over";
print "the";
print "moon";
Here's the result:
The -?- cow -?- jumped -?- over -?- the -?- moon -?-
Similar, though not identical, is the output field separator, which is used
to specify the delimiter between the different values specified in a single
print() command. This value is stored in the $, variable, and is usually
null. Consider the following example, which demonstrates how it can be used:
#!/usr/bin/perl
# set output field separator
$, = ":";
# print output
print "The", "cow", "jumped", "over",
"the", "moon";
Here's the output:
The:cow:jumped:over:the:moon
A common use of these two variables is to customize the output of the
print() command - as in the following example:
#!/usr/bin/perl
# load module
use DBI();
# connect
my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost",
"root",
"secret", {'RaiseError' => 1}) or die ("Cannot connect to
database");
# query
my $sth = $dbh->prepare("SELECT name, age, sex FROM users");
$sth->execute();
# set separators
$, = ":";
$\ = "\r\n";
# print data as colon-separated fields
# each record separated by carriage return
while(my $ref = $sth->fetchrow_hashref())
{
print $ref->{'name'}, $ref->{'age'}, $ref->{'sex'};
}
# clean up
$dbh->disconnect();
Here's the output:
john:34:M
jimmy:21:M
john:31:F
jane:27:F
Sure, this is a very complicated way of doing something really simple - but
hey, it's an example. Don't take it too seriously!
Next: Getting Into An Argument >>
More Perl Articles
More By icarus, (c) Melonfire