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

Answer to chapter 12 question 2

As for the Awk solution, there are many other possible solutions to the Perl problems.

$available_chars=72;
$output_line="";
while (<STDIN>) {

  # remove newline
  chomp;

  # remove leading spaces
  $_ =~ s/^[ ]*//;

  # remove trailing spaces
  $_ =~ s/[ ]*$//;

  # create an array of the words on the input line
  @words=split;

  # loop through the words in turn ...
  for ($i=0; $i <= $#words; $i++) {
    $word = $words[$i];

    # ... and if it will not fit on an output line ...
    if (length($word) >= $available_chars) {

      # ... print the current output line ...
      print $output_line . "\n";

      # ... and reset the variables
      $available_chars=72 - length($word);
      $output_line=$word;
    }

    # add the word to the output line (not forgetting a
    # blank space) and reset the variable storing the
    # available space
    $available_chars = $available_chars - length($word) - 1;
    $output_line = $output_line . " " . $word;
  };
}
print $output_line . "\n";

Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck