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.
Another very useful variable is the $/ variable, which Perl calls the input record separator. The $/ variable contains one or more characters that serve as line delimiters for Perl; Perl uses this variable to identify where to break lines in a file.
In order to illustrate, consider the following sample password file:
By default, the $/ variable is set to the newline character. Therefore, when Perl reads a file like the one above, it will use the newline character to decide where each line ends - as illustrated in the following example:
#!/usr/bin/perl
# read file into array
open (FILE, "dummy.txt");
@lines = <FILE>;
# iterate over file and print each line
foreach $line (@lines)
{
print "--- " . $line;
}
# print number of lines in file
$count = @lines;
print "$count lines in file!\n";
Now, if you alter the input record separator, Perl will use a different delimiter to identify where each line begins. Consider the following example, which sets a colon (:) to be used as the delimiter, and its output, which illustrates the difference:
#!/usr/bin/perl
# set input record separator
$/ = ":";
# read file into array
open (FILE, "dummy.txt");
@lines = <FILE>;
# iterate over file and print each line
foreach $line (@lines)
{
print "--- " . $line;
}
# print number of lines in file
$count = @lines;
print "$count lines in file!\n";