dcsimg

Dealing With Records in Perl

By Juliet Kemp (Send Email)
Posted Nov 30, 2009


One thing Perl does really well is read in information from a file. There are a couple of useful special variables you can use to neaten up your code when doing this or to alter the default behavior when reading in records.

Tip of the Trade: Perl is a great tool for reading in information from a file. Several useful special variables can be used to neaten up code or alter the default behavior when reading in records.

The first is the special variable $.. $. keeps track of your current record number while iterating through a file. Thus:

while(<FILE>) {
    print "Current line number is $. n";
}
Using this saves setting up a separate variable to keep track.

The above example uses the default behavior, which reads in a file line-by-line. This behavior can be altered by setting $/, which is the field separator, set to newline by default. For example, you could set it to read records separated by a semi-colon, instead:

$/ = ";";
while (<FILE>) {
    print;
}

However, bear in mind that changing this variable will affect all code until the program finishes — which might be particularly awkward (and bug-introducing) if you're writing a module that will interact with other code. To avoid this, use the function local, which creates a temporary local variable with the same name as an existing variable:

{
    local $/ = ";";
    while (<FILE>) {
        print;
    }
}
The scope of local is the naked code block created by the outside { }. Once outside the block, $/ is back to whatever it was before. In fact, whenever you're setting special variables to non-default values, it's wise to use local like this.

A final note: Bear in mind that $. tracks records, not line numbers. Thus, if you reset $/, $. will increment according to your new record delimiter.

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


Comment and Contribute

Your name/nickname

Your email

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