- 1 Tips and Tricks for Detecting Insider Threats
- 2 Red Hat Enterprise Linux 7.5 Debuts with Improved Server Admin Features
- 3 Opportunity Lost: Enterprises Could Slash Cloud Costs by 36 Percent
- 4 Intel Sheds Wind River Embedded Division
- 5 Linux 4.16 Released with Improved Security, Virtualization Features
Dealing With Records in Perl
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"; } |
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; } } |
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).