Automatic File Conversions with Perl
by Tim Kientzle



Figure 1: 

(a) lpd -> PrintConvert

(b) lpd -> PrintConvert -> uncompress -> 
                 PrintConvert

(c) lpd -> PrintConvert -> uncompress -> 
                PrintConvert -> lptops -> PrintConvert

(d) lpd -> PrintConvert -> uncompress -> 
                PrintConvert -> lptops -> PrintConvert -> printer


Example 1: 

} elsif (/^\037\213/) {                 # GZIP
    &PrintTo("|gunzip | $0 @ARGV");


Listing One
#!/usr/bin/perl
# PrintConvert -- convert any file type into printer output

# Read the initial section of the file
$blocksize=16384;
sysread(STDIN,$_,$blocksize);
$first_segment = $_;
if (length($_) == 0) { exit(0); }

# Now, use those initial bytes to determine the file type and
# appropriate handling.
# Note that "$0 @ARGV" is the current program and options.  Most
# formats are fed through some conversion program and then into
# another copy of this program for further consideration.

if (/^\004?%!/) {                       # PostScript, possibly preceded by ^D
    &PrintTo(">-");                     #   just dump it to STDOUT
    print STDOUT "\004";                #   append Ctrl-D
} elsif (/^\037\213/) {                 # GZIP
    &PrintTo("|gunzip | $0 @ARGV");
} elsif (/^\037\235/) {                 # Unix Compress
    &PrintTo("|uncompress | $0 @ARGV");
} elsif (/^\367\002/) {                 # TeX DVI format
    &PrintTo(">/tmp/PrintConvert.tmp.$$");     # Save into temporary file
    exec "dvips -q -f </tmp/PrintConvert.tmp.$$ | $0 @ARGV";
} elsif (/^\115\115/) {                 # TIFF file
    &PrintTo("|fax2ps | $0 @ARGV");
} elsif (/^\111\111/) {                 # TIFF file
    &PrintTo("|fax2ps | $0 @ARGV");
} elsif (/^\314\000\206/) {             # FreeBSD executable (don't print)
    print STDERR "Executable file not printed!\n";
} else {                                # Unrecognized text file
    &PrintTo("|lptops -ntr | $0 @ARGV");              # Use lptops

}
# `Print' data to the named destination
sub PrintTo {
    open(OUT,"@_");                     # Open the file or program
    syswrite(OUT,$first_segment,length($first_segment)); # Write first segment
    while(sysread(STDIN,$_,$blocksize)) {    # Now copy the rest
    syswrite(OUT,$_,length($_));
    }
    close(OUT);
}

2


