Perl comes with a whole bunch of cryptically-named built-invariables, which clever Perl programmers exploit to reduce the number oflines of code in their scripts. This article examines some of the morecommonly-used special variable in Perl, with examples and illustrations ofhow they may be used.
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:
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:
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!