Example nine: Subroutines

# Example nine - Subroutines.
# A simple subroutine to split input lines: how to create and call.
# It also introduces the substitute expression.
# by Al Bento

$infile = "example8.txt";
$outfile = "example9.txt";

open (READ, "<" . $infile) || die "Could not open file to read\n";
open (WRITE, ">" . $outfile) || die "could not open file to write\n";

print "This is the printout of the data written to the new file\n\n";

while (<READ>) {chop;
       &divide;    # calls the divide function
       print WRITE "$name likes $color\n";
       print "$name likes $color\n";

close (READ);
close (WRITE);

# example 8 has not taken care of blanks after the name and after the
# color. The divide function will split the line and remove blanks,
# if any.

sub divide {
       ($name,$color) = split (/=/,$_);
       $name =~ s/\W.*//; # remove blanks after first word
       $color =~ s/\W.*//; # remove blanks after second word

#      \w matches anything valid in a variable name in Perl,
#             while \W matches the opposite
#        . matches any single non-newline character
#        * means zero or more of the previous character
#        // means we are substituting for nothing (deleting)

download the script

This page is maintained by Al Bento who can be reached at abento@ubmail.ubalt.edu. This page was last updated on June 15, 1997. Although we will attempt to keep this information accurate, we can not guarantee the accuracy of the information provided.