Member of the Programming Republic of Perl

GuyMcArthur.com: Sample Perl Source Code

I've used Perl a great deal since 1995. There doesn't seem to a limit as to what you can do with Perl, or to how advanced a Perl programmer can become. This is just a collection of some of the more interesting things I've done with perl as I've learned it. More code will be posted as time permits.

I'll be glad to answer any questions concerning Perl. Please check the Perl FAQ's first and check CPAN site to see if a module exists than can simplify things. If you can't find a solution, feel free to email me.

The following programs are distributed for free under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

These programs are distributed in the hope that they will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

For a copy of the GNU General Public License, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

Abstract Source Code
Dynamic VRML Creation
GearMaker uses Math::Trig (now standard with Perl) and Hartmut Palm's excellent VRML::VRML2 module to dynamically generate a 3D model of a gear given the following input. A VRML97 plugin such as Cortona 4 is required. See my VRML page for more cool models.
# of Teeth: (Integer)
Sharpness: % (Percentage)
Height: (Decimal)
gearmkr.pl
Dynamic Image File Creation
Starfield generates a simulated field of stars, writing out a GIF file. The frequency of stars of a given magnitude is set in the program. Use the form below to see an example It doesn't look very realistic unfortunately. To do it right, you need to use a blend of grayscale pixel values instead of all white. Also, the real night sky is more "clumpy" than a purely random distribution.
WIDTH: HEIGHT:
starfield.pl
Sendpage: Email A Web Page

This utility fetches a web page and sends it to the specified recipient as an attached HTML page. I use this every morning, in a cron process, to email myself things like cartoons, job listings, etc. It's pretty smart about figuring out the "base href" so images, links and embedded objects show up just fine.

Options:

            -t To email address (recipient).
                -f From email address (sender).
                -c CC email address (quote if it's a list).
                -s subject line (quote it).
                -b base href (if needed to override)

Here is example use in a UNIX crontab:


25 07 * * 1,3,5 ${HOME}/bin/sendpage.pl -t ${LOGNAME} \
-s "Joy of Tech" http://www.geekculture.com/joyoftech/
30 06 * * * ${HOME}/bin/sendpage.pl -t ${LOGNAME} -c mary@seds.org \
-s "Astronomy Pic of the Day" \
http://antwrp.gsfc.nasa.gov/apod/astropix.html

sendpage.pl
Perl One-liners
Sometimes you want to do something fairly simple in concept, without writing a whole program to do it. Perl offers a fantastic utility to do this: the one-liner. I challenge you to provide simpler cases in other languages (using standard UNIX or GNU tools is okay)!
Lowercase everything within a directory (branch-first recursion).

perl -MFile::Find -e 'finddepth( sub { rename $_, lc $_; }, ".");'

Fetch a numbered series of images (with leading zero) from a web page.

perl -e 'foreach (0..20) { $N=sprintf "%02d"; qx(wget http://hotporn.site/image_$N.jpg); }'
Simple Network Management Protocol

SNMP is anything but simple. But it is extremely powerful. From over the network you can query all sorts of information about a server. Such as cpu load averages, memory usage, disk usage and process information. Click here for a sample. That's generated dynamically from the snmp.pl example which uses the SNMP perl module. Other information includes fine details on the TCP/IP stack performance and a whole lot more.

And that's just the tip of the iceberg. The "management" in SMTP means that the server can respond to events by invoking commands.

Routers and cable modems typically have SNMP built-in. There's a program called MRTG that can create live graphs of SNMP data (which on a server could include any of the above, e.g. cpu load). Another perl program called Mon can monitor all kinds of things (SMTP parameters are just one class) and perform alerts, such as sending pages or email to your phone.

SNMP, MRTG and Mon are all open source. Linux distributions usually ship with the UC Davis implementation of SMNP, which is the best, and provides "MIBs" (I forget what it stands for) for fetching all the data you see in the sample. Sun has there own SNMP daemon; uninstall it because the UCD one is better (and easy to build/install). By default the data is private and read-only (otherwise h/\|<3rs would have an easy time with your system).

The code here probably could be simplified greatly (and the gratuitous use of references doesn't help). Originally it was doing charts but I stripped it down to the bare html output.

Oh, it also demonstrates perl's error handling (using eval and $@).

SNMPstat.pm snmp.pl
Automatic MP3 URL Playlist
WinAMP, MacAMP, XMMS and other MP3 audio players can load a playlist of mp3 urls. This CGI uses the File::Find module to built such a playlist. It can be done dynamically (invoked from the player). This is useful if you're sharing a bunch of mp3's on the web (of course, you'll want to make sure access is protected so jack-booted RIAA thuds don't come knocking on your door)!
autolist.cgi
DOS 2 UNIX and UNIX 2 DOS
This file converts ``Macintized'' text files with ctrl-m chars into UNIX text files with newlines, or converts newline text into ctrl-m. I.e. it goes back and forth between CRLF and LF end-of-line markers much line the venerable dos2unix command (available for UNIX and Windows). The default is to work like dos2unix, but this can be reversed with the -m command switch.

Options:

        -m Convert UNIX newline chars into Macintosh ctrl-M chars

sourcefile is, of course, the name of the file you want read. destinationfile is the name of the file you want written.

If no destination file is given, the source file is converted in place.

mactext.pl
Dynamic Image Browsing
Image Browser is more than just another dynamic image displayer. It's "automatic" in the sense that you can just copy it into a directory, and voila! you can browse through the images in that directory over the web. It's intended to be used through Apache's high performance Perl engine called mod_perl, in which case it will "stat" the directory only the first time it is invoked, or when the directory is modified (e.g. an image is copied into or moved out of the directory). But it can also be used as a normal CGI. It also demonstrates use of references (pointers) and anonymous subroutines.

Click here for a demonstration

images.pl
Interaction With Web Pages
Using LWP (LibWWW Perl) you can interact with web sites (such as posted to an html form handler), even using basic authentication. My ex-employer had a "project tracker database" that we were required to log into every morning and log out of every night. I wasn't too good at remembering to do that, so I wrote this script to do it for me.
tracker.pl
User Account Management
Adduser simplifies the creation of UNIX user accounts on our system. It creates the account and home directory, adds the user to the specified groups and mailing lists. Some day maybe I'll do it properly with a real menuing system, the ability to add entries with Net::LDAP, and more. Also, it's about the first thing I ever wrote in perl, so the code is pretty lame.
adduser.pl
Date Calculations
Age returns the number of days difference from today to a given date, using the Date::Calc module. Very simple, just one function call.
Date:
age.pl
Web Robots
APOD gets the latest "Astronomy Picture Of the Day" from the web, resizes it, saves it as a JPEG and FTP's it to another machine. It demonstrates the Image::Grab and Net::FTP modules.
apod.pl
Database Interaction
DBI is the module to use in perl for databases. Drivers are provided by the DBD series, e.g. DBD::Oracle and DBD::mysql. I'll post some examples here in the near future.
 
Web Interface to Sendmail
Feedback handles web-posted email messages for my site. It does some rudimentary error checking, making sure email address's and URL's at least look valid. More detailed documentation is available and you can try it below.
feedback.cgi
URL Validation
Validate checks to see if an input URL is good (the web server is running and the document or directory exists).

Header returns the HTTP response headers from a web server given as a URL on the command line. Sourcer outputs the body of the web page (or full error message if possible). They demonstrate simple use of the LWP library and the creation of a custom user agent.

URL:
validate.pl
header.pl
sourcer.pl

Last Updated: December 2001.

Need help with Perl? Send me your questions?