dcsimg
October 23, 2018
Hot Topics:

Cross-platform Perl/CGI tips and tricks

  • December 4, 1998
  • By Dave Edis
  • Send Email »
  • More Articles »

Another issue is that Windows treats binary files and text files differently, so if you're trying to read or write a binary file, you'll get corrupted data, unless you specify that the file is to be read or written in binary mode.

### Read Binary file on Windows
open(FILE,"<$cgidir/image.gif");
binmode(FILE);       # Specify Binary mode for file
binmode(STDOUT);     # Specify Binary mode for output
print "Content-type: image/gif\n\n";
while () { print; }
close(FILE);

Unix doesn't pay attention to "binmode," so it won't cause problems by having it in there, it will just make Windows systems recognize the file as binary and read/write it correctly.

Perl replacements for common system commands

I've seen many CGI programs that would work beautifully on any server except for one simple thing. Where the programmer needed to copy, rename, or erase a file, instead of doing it in Perl he just used an operating system specific shell command (e.g.,
system("cp $file1 $file2");
). Not only does this make the program only work on Unix, it also poses a potential security issue when you pass unchecked variables to the shell.

Here are some 100 percent Perl-based alternatives to common system commands that will work on any operating system.

### ERASE
unlink("$cgidir/file.dat"); 

### RENAME
rename("$cgidir/oldfile.dat","$cgidir/newfile.dat"); 

### COPY
open(FILE1,"<$cgidir/file1.dat");
open(FILE2,">$cgidir/file2.dat");
binmode(FILE1);
binmode(FILE2);
while () { print FILE2; }
close(FILE1);
close(FILE2);

### CHMOD
chmod(0777,"$cgidir/file.dat"); 

### MAKE DIRECTORY
mkdir("$cgidir/newdir",0777); 

### REMOVE DIRECTORY
rmdir("$cgidir/newdir"); 

### CURRENT DATE/TIME
$date = scalar localtime(time);
print $date;  

By using a few simple tricks and tips like these, you'll not only be saving time but writing better programs too! If you have any tricks and tips of your own you would like to share, drop me a line.

Dave Edis is president of Edis Digital, a new media solutions firm in Vancouver, Canada. Edis Digital develops Web-based publishing tools and applications for companies around the world.






Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

By submitting your information, you agree that developer.com may send you developer offers via email, phone and text message, as well as email offers about other products and services that developer believes may be of interest to you. developer will process your information in accordance with the Quinstreet Privacy Policy.

Sitemap

Thanks for your registration, follow us on our social networks to keep up-to-date