Wordsmyth's Corner

Perl Primer - Chapter 5 -

by Linda Naughton

Topics
Previous Chapter Next Chapter


User Input

Standard input can be read from a stream using the <STDIN> syntax.
   print "Enter name:\n";
   $name = <STDIN>;
This will get one line of data, including the newline marker (\n).

Chomping Newlines

The chomp function will strip off a newline at the end of a string. If the last character is not a newline, it does nothing.
    $name = <STDIN>;
    chomp($name);
chop is similar, but will take off ANY last character, whether it's a newline or not. This makes it pretty useless in my experience.

Command Line Arguments

The @ARGV array stores command line arguments. There is no ARGC equivalent, but remember that you can get the array count by using the array name in a scalar context.
    if (@ARGV != 2)
    { 
    print "Oh no! I was expecting 2 arguments!\n"; 
    }
    else
    { 
    print "Arguments OK: $ARGV[0] and $ARGV[1]\n"; 
    }

Options Package

A better way of parsing options is to use the options package.
  use Getopt::Long;
  $result = GetOptions ("length=i" => \$length,
                        "file=s"   => \$data,
                        "verbose"  => \$verbose); 
This expects the user to pass options in the form:
   program.pl -length 22 -file "file.dat" -verbose
Length will be interpreted as an integer, file as a string, and verbose will be set to 0/1 depending on whether the "-verbose" option was provided.

All options are considered optional. They will be set to undef if they are not provided. If you want to require options, you must check for them manually.

TRY IT: Command Line Input

File Handles

Use the open function to open a file for input or output.
    open(INFILE_HANDLE, "filename");
INFILE_HANDLE is a special kind of variable: a file handle. It doesn't need to be declared using "my" (in fact - it can't!). It is global to the entire file.

Add the ">" character in front of the filename to open a file for output (erasing what's already there).

    open(OUTFILE_HANDLE, ">filename");
Ad the ">>" characters in front of the filename to open a file for output and add to whatever's already there.

Always close a filehandle when you're done.

    close(OUTFILE_HANDLE);

File Input

You can read an entire text file into an array with one statement.
    @fileLines = <INFILE_HANDLE>;
Each line of the file becomes an item in the array.

You can also operate on the file line by line with a while loop.

    while ($line = <INFILE_HANDLE>)
    {
    print "Line: $line\n";
    }
(Parsing binary data is beyond the scope of this primer.)

TRY IT: Reading a text file

File Output

Printing to the output file can be done using the standard print statement. Just add the output handle in front of the text to print.
   print OUTFILE_HANDLE "My output.";

TRY IT: Output to a file

Executing System Commands

Putting a command in backquotes will cause Perl to execute it as if it were a system command. The output of the command can be stored into a variable.
    @dirLines = `dir`;
    print @dirLines;       # Prints output of dir.
You can also use the qx() function to quote a string in backquotes.
    @dirLines = qx(dir);   # Same as above
Backquotes and qx are often tempermental about interpolating variables (particularly concatenating strings). A way around that is to use an intermediate command line string.
    $commandLine = "dir";  # Set up a command line.
    qx($commandLine);      # Execute it.

Other File Utilities

Perl has a ton of shortcuts for basic file operations. Some of the common ones:
   -e $name      # File or dir name exists
   -d $name      # Entry is a directory
   unlink $name  # Deletes a file

File Errors

If a file operation fails, you can get its error using the $! operator. The usual syntax is:
   open(FILE_HANDLE, "filename") or 
      die "File open failed!  $!";
Previous Chapter Next Chapter