Main index

Introducing UNIX and Linux


Perl

Overview
Introduction
      Why yet another utility?
      Beginning Perl
      Invoking Perl
      Documentation on perl
      Perl Scripts
Variables
Input and output
      Files and redirection
      Pipes
      The DATA filehandle
Fields
Control structures
Predefined Perl
      Functions
      Modules
Regular expressions
      Single character translation
      String editing
Perl and the Kernel
Quality code
When do I use Perl?
Summary
Exercises

The DATA filehandle

The DATA filehandle allows access to data in the same physical file as the Perl program itself (similar to a shell "here" document). The program and data should be separated by a line containing the string __END__, and unlike the shell this terminator cannot be changed to a different one.

Worked example

Write a Perl script to read into an array @days the names of the seven days of the week and then display them on standard output.
Solution: Use the DATA filehandle and place the data at the end of the Perl script. One loop is needed to do both the assignment and the printing.

# Set variable i to count the lines of data read in
$i=0;

# Repeatedly read lines of data
while (<DATA>) {

    # Remove the trailing newline character
    chomp($_);

    # Set the array value indexed by i to the line
    $weekday[$i]=$_;

    # Print the line on standard output
    printf "$weekday[$i]\n";

    # Increment i
    $i++;
}
# The Perl program ends and the data follows
__END__
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck