Introducing UNIX and Linux |
PerlOverview |
Answer to chapter 12 question 2As 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