Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Miscellaneous

by vroom (Pope)
on May 26, 2000 at 01:08 UTC ( #14867=sourcecodesection: print w/ replies, xml ) Need Help??
File::DumbLock
on Sep 15, 2002 at 21:40 UTC
by PodMaster
update: use File::FlockDir instead (i am).
File::DumbLock - dumb locking mechanism (lock if file not exist)

File::DumbLock implements the dumbest kind of "locking" mechanism known to man. It's voluntary, and it can backfire, but virtually every plaform suports it.

Every time you "obtain a lock", a semaphore is created (a lockfile). Every time you "release a lock", that semaphore is deleted (if possible). If the lockfile can't be deleted, you'll be warned, but you'll lose the lock.

Example: my $dumB = new File::DumbLock(name => 'file' ); my $dumC = new File::DumbLock(name => 'file', wait => 2 ); print "dumB got lock\n" if $dumB->Open(); sleep 2; print "dumC stole lock\n" if $dumC->Open(); print "dumB couldn't get lock\n" unless $dumB->Open();

You can download it at File-DumbLock-0.01.tar.gz sometime soon.

update: If you know of a module that already exists that does this, please /tell me.

I am also entertaining name suggestions: Lock::Dumb, Lock::Semaphore, Lock::Simple, File::SimpleLock ...

update: It appears i won't be changing the name. DON'T USE THIS CODE did make me chuckle heartily.

rename
on Sep 02, 2002 at 02:52 UTC
by jjdraco
will take a list of directory names that are subdirectories to the location of rename.pl and rename all image files in thoses directories to directoryname####.ext

this is my first program written in perl, don't know if any one would have a use for it but i would like some feedback.
use Drugs;
on Aug 30, 2002 at 17:01 UTC
by Dylan
Drugs is a perl module that makes existing perl scripts more interesting. I'd be interested if anyone else finds this funny... "This is your script, this is your script on drugs" <g> Update: Modifed to be less C-like (Thanks, Aristotle).
Update: Fixed sprintf thing.
Uniqueue
on Aug 29, 2002 at 09:29 UTC
by Zaxo

This is an implementation of a FIFO with unique elements. It was suggested by BrowserUK's RFC and debugging tips, though it does not share all properties of his uFIFO class. In particular, it is not rewindable and uniqueness is only enforced for elements presently on the queue.

Further description is in the pod.

Update: Version 0.03 -- constructor new rewritten in terms of enqueue to allow easier subclassing. Override enqueue in the child class and new will initialize using the child's version.

 

MIDI controller generator
on Aug 25, 2002 at 10:50 UTC
by Django

This node is obsolete!
A completely rewritten and enhanced version can now be found here:
http://dmcgen.bitrock.net/
The original posting below remains unchanged - just ignore it.


This is a tool for musicians to generate MIDI controller variations. The program takes a template MIDI file, or a simple plain text representation of that, and generates from the given "Alpha" and "Omega" values a given number of variations, using the algorithms "random", "morph" or "switch". A typical use for that would be to create random settings of certain controllers of an instrument within a specified range.

You can copy the POD "for example.txt" at the end of the code and use it as template text file.

Instead of a one-line command or a GUI I've made up some kind of "talking shell", who asks you for one argument after the other, reports and provides a short help text.

It's my first "more than few lines" perl program and as you may see I'm experimenting with vertically oriented formatting to increase readability - an even spacier version of the code is on my Scratchpad. I would be glad to hear your oppinion concerning that. I know that there could be some structural improvement - please tell me if you find any major do-nots or not very elegant phrases.

I'd also welcome suggestions where else to post a tool like that.

nmap bot
on Aug 20, 2002 at 12:35 UTC
by mousey
This bot runs on the AIM (AOL Instant Messaging) network and when spoken to, runs nmap based on the instructions given to it. You need Net::AIM and nmap installed.
Yet Another Newbie Code...
on Aug 18, 2002 at 22:57 UTC
by majin
Takes any file as an input and adds it to a file thats acts as a wordlist. This word list has several "uses"... I shall not tell about these uses as it might give some wannabies ideas but those who need it shall know it...
Very Simple Stack-based Language
on Aug 17, 2002 at 00:26 UTC
by orkysoft

I made this after reading this post about using a simple stack-based language. The author described the language, but didn't provide any code, and I thought I could write some code quickly, so I did.

It's not very fancy, but it does seem to work. It's also not well-tested yet, but I don't expect to encounter serious bugs. :: crosses fingers :: ;-)

It's been updated a couple of times now :-)

Simple autoflush module
on Aug 12, 2002 at 18:48 UTC
by RMGir
I do a lot of one-liners, and often want Autoflush turned on.

But typing

perl -ne'BEGIN{$|=1}...'
for each is a bit of a pain, so I wrote this so I can do
perl -MAF -e'...'
instead.

I could always do

perl -ne'$|=1;...'
but that's probably very inefficient.

The name is short, since calling it "Acme::Autoflush" would pretty well defeat the purpose.

AIM Offline Messaging Bot
on Jul 22, 2002 at 21:49 UTC
by mousey
This bot will stay online. People can contact the bot and leave messages for someone. When the person that the message was left for signs on, the message will be sent with the screenname of the person who left it. Stats of the bot are stored in the profile.
Google Search AIM Bot
on Jul 20, 2002 at 12:51 UTC
by mousey
This is a Google Search AIM bot. You send IMs to it and it returns the first 5 results of what you send it. You must have Net::AIM, the Google Dev Kit, and an AIM screenname.
Balance columns
on Jul 12, 2002 at 00:02 UTC
by merlyn
Ovid recently posed a puzzle about how to minimize the text in an HTML table. While many solutions had been posed, I kinda like the way I finally solved it while sitting in a recent meeting of the pdx.pm group when I should have been listening to chromatic give his talk.
Simple HTML doc retrieval and analysis script
on Jun 10, 2002 at 08:09 UTC
by cjf

Simple HTML document retrieval script. Takes a url and a keyword as args, grabs the document, archives it in a directory hierarchy, does a very simple (soon to be improved) analysis for the specified keyword, and returns a relevance score. As always, suggestions for improvements are appreciated.

Chemistry Elements Quiz
on May 23, 2002 at 14:03 UTC
by cjf
Simple command line quiz using Chemistry::Elements. Provides you with either the element name, symbol, or atomic number and asks you for the other two. All suggestions (especially those dealing with the 3 repetitive subs) are greatly appreciated.
Word Count Script+
on May 22, 2002 at 15:07 UTC
by xgunnerx
A word count script that "attempts" to be more accurate. It will take into account works at the end of a line that end with a hyphen, words that contain hyphens, etc. It will also give a character frequency on every character. A word frequency on every word. Avg length of words. Avg amount of words per sentence. Results go in results.txt
Infix/Postfix Notation
on May 20, 2002 at 14:42 UTC
by xgunnerx
A script that does infix/postfix polish notation. Define the notation on line 5. Enjoy!
Sub::Lexical
on May 15, 2002 at 19:34 UTC
by broquaint
Now available on CPAN - Sub::Lexical

See the POD for info about the module.

Basically I'm just throwing this out to see if anyone can find any use for this since it's really just syntactic sugar. There's still a couple of bugs but they should go if I ever bother putting it somewhere important like CPAN or the Code Section on Perl Monks. Hey wait a second ... And if anyone actually wants to play about with it a bit further I can provide them with an actual package (tests and all!)

Any improvements/suggestions/condemnations welcome

A better (?) uudecoder.
on Apr 27, 2002 at 03:16 UTC
by mephit
"Better" than the uudecode that comes with Linux, anyway. This script that will take a text file filled with uuencoded data (even multiple files, and with non-data as well, as if saved from Usenet) and uudecode each file found. Useful for me, anyway. Uses Convert::UU. Comments or questions? Leave a message at the beep.
Template::Plugin::PerlTidy
on Apr 25, 2002 at 23:31 UTC
by OeufMayo
This modules is a Template Toolkit Filter for Perl::Tidy. It can be used to automatically display coloured and formatted perl code in web pages.
Attribute::Default
on Apr 24, 2002 at 08:01 UTC
by stephen

Inspired by the discussion about subroutine defaults, I decided to write this...

You've probably seen it a thousand times: a subroutine begins with a complex series of defined($blah) or $blah = 'fribble' statements designed to provide reasonable default values for optional parameters. They work fine, but every once in a while one wishes that perl 5 had a simple mechanism to provide default values to subroutines.

This module attempts to fill that gap. It allows you to declare your subroutines with a 'default' attribute which you can use to specify whatever default values your subroutine should have, and automatically fills them in if they are undefined or not provided. It works on simple scalar arguments, list arguments, and hash-style named arguments.

Used like this:

use base 'Attribute::Default'; sub say_name : default('stephen') { my ($name) = @_; print "Hello, my name is $name\n"; } # Prints "Hello, my name is john" say_name('john'); # Prints "Hello, my name is stephen" say_name();
Finding the Distance between longitude and latitude pairs
on Mar 07, 2002 at 16:37 UTC
by cacharbe
A while back my younger sister asked me to help her with homework from her college trig course. She had to solve a Great Circle Distance problem. After showing her the steps, it got me to thinking, and then reading, and then finally coding. What I found was quite interesting, and from that research spawned an application to find the distances between to corporate locations from their zip codes that I implemented on our intranet.

There are actually a couple of different methods for determining the distance between 2 long/lat pairs and you need to be aware of the accuracy of each. The Great Circle method is the least accurate IIRC, but is the most accessible, as it is a part of Math::Trig. I wrote some code to do this using the various methods. As I mentioned, it finds the distances between two zip codes for which the long/lat pairs are known, but I've removed the database interface for brevity and just given the pertinent code. You should also read: this, this and (my favorite) this article.

I was pretty explicit in my code so that my non-programming sister could understand it when I showed it too her to explain the different algorithms, but I think it gets the point across.

C-.

Magic Status Variable
on Mar 01, 2002 at 23:56 UTC
by particle
MagicStatus.pm allows you to tie a scalar variable that will warn when it is assigned a value you wish to watch. One use might be to track and debug the return status from a function.

since it's taking more than a month for me to get my CPAN id, i'll post here first. all comments are welcome.

Update: added rjray's suggestions, released as Revision 1.1

Update: added abaxaba's suggestion (silly me, i should have caught that!)

XPM (X Pixmap) stats
on Feb 20, 2002 at 07:51 UTC
by rjray

This is something I recently found while "cleaning house" in my /home prior to a disk upgrade. It reads the data parts of an XPM file and gives a simple accounting of the colors used in the pixmap, sorted in descending order of frequency. It's short and simple, so you should be able to adopt and/or adapt whatever parts you may have need for into other areas.

My original reasoning for it was when I was more fond of using background images on webpages. I tended to use marble patterns, faux-paper patterns, etc. I wanted to set a background color that was as close to the overall image as possible, so that people having network problems could still read the text even if the background hadn't loaded yet. Nothing worse than yellow text on a white background while you wait for that near-black background tile to finish loading. Basically, I grew tired of loading the image in sxpm or XV and rolling the mouse over it while guessing at which of the color specs was really showing up the most.

--rjray

SiteConfig Module
on Feb 18, 2002 at 20:59 UTC
by impossiblerobot
SiteConfig - Perl module for XML-based site-wide configuration files

SiteConfig was created as a simple way to manage site-wide configuration information, allowing multiple applications to share various sub-sets of the overall settings.

Though I've been using this for a while, I've never posted it because there are so many configuration management modules on CPAN. But I've found it so useful that I decided others might like it too.

I've used it for things I had not anticipated; for example, loading a hash from an XML file of state names and abbreviations.

For more information, read the POD (at the end of the module code -- though normally I keep the POD for this module in a separate file). I would appreciate any suggestions/comments that would help me improve this.
Amino acid sequence builder
on Feb 16, 2002 at 10:19 UTC
by runrig
This was inspired by a puzzle in Dr. Dobb's Journal where you are given an amino acid sequence to build from a collection of nucleotide sequences. You are allowed to 'glue' together nucleotide sequences n times, and allowed to 'splice' on a total of m single nucleotides to your sequences before gluing. This implementation doesn't quite follow the rules in the original puzzle, but I didn't feel like changing the program since it does produce the correct results (AFAIK) for the given parameters. If it did generate some incorrect results, they could easily be filtered out anyway (finding exactly what is non-conformant is an exercise left for the reader). Comments, both on the code and on how useful this is in the real world (and on what a more appropriate module name would be), are welcome.

Update: Someone pointed out I was missing some codons. Added them :-)

Linux ioctl command module
on Jan 24, 2002 at 03:56 UTC
by Zaxo

This is a translation of the bit-twiddling functions used to produce an ioctl command in Linux. See your linux.pl file for another approach. Device numbers are not so static any more.

UNIVERSAL::extends
on Jan 11, 2002 at 23:23 UTC
by miyagawa
Syntactic sugar of base.pm for Java programmers.
Gradebook Plus parsing module.
on Jan 04, 2002 at 07:46 UTC
by jryan

Gradebook is a module useful for parsing Gradebook Plus text reports, a program used by many K-12 school districts. Simplely go to Reports->Gradebook of entire Class->(check fancy report, catagory totals, and sum/pct/grade)->Save to disk. The parser can then parse the contents of this file. Use it how you like; I use it so teachers can put their grades online with minimal effort on their part. It is fairly robust (especially considering the extremely unfriendly formating parsing-wise) and has methods to access all data for your convience. Note that parsing this isn't as easy as it looks; when the report gets to more than 80 columns it wraps itself to a new page. You can have up to 90 grades, which can be up to 10 pages in length. To make it even more fun, the pages are just concatrated one after another. Hence the need for a module :) Read the pod for more info. Also, you can find yourself a copy of Gradebook plus at:http://www.svemedia.com/demo.html


Update:A Sample Gradebook dump (as suggested by crazy: (this is the Gradebook supplied in the demo with 2 records added)

Carlmont School Kingsfield's Per 7 Government Gradebook as of Fri Jan 4, 2002 Name 1 2 3 4 5 6 7 Total Pct. -------------------------------------------------------------------- Adams, John 10 10 13 9 76 30 3 151 82.5 Adams, Quincy 10 10 12 9 67 30 3 141 77.0 Cleveland, Grover 10 10 11 10 68 30 3 142 77.6 Coolidge, Cal 10 10 14 10 82 30 3 159 86.9 Eisenhower, Dwight 10 10 15 10 93 30 3 171 93.4 Fillmore, Millard 10 10 16 10 100 30 3 179 97.8 Ford, Jerry 10 10 19 ( ) 93 30 3 165 90.2 Grant, U. S. 10 10 18 10 68 30 3 149 81.4 Harding, Warren 10 10 17 10 73 30 3 153 83.6 Hoover, Herb 10 10 20 10 92 30 3 175 95.6 Jackson, Andy 10 10 20 10 95 30 3 178 97.3 Jefferson, Tommy 10 10 19 10 78 30 3 160 87.4 Kennedy, Jack 10 10 16 10 72 30 3 151 82.5 Lincoln, Abe 10 10 18 10 75 30 3 156 85.2 Madison, Jim 9 10 14 10 80 30 3 156 85.2 McKinley, Bill ( ) 10 12 10 70 30 3 135 73.8 Monroe, John 10 10 16 5 93 30 3 167 91.3 Pierce, Frank 9 10 18 8 83 30 3 161 88.0 Polk, James 9 10 15 9 68 30 3 144 78.7 Roosevelt, Frankie 10 10 19 10 73 30 3 155 84.7 Roosevelt, Teddy 10 10 17 10 72 30 3 152 83.1 Truman, Harry 10 10 17 10 77 30 3 157 85.8 Tyler, John 10 10 10 9 88 30 3 160 90.9 Washington, George ( ) 10 14 10 79 30 3 146 79.8 Wilson, Woody 10 10 17 10 72 30 3 152 83.1 Average : 9 10 16 19 79.5 30 3 155.4 85.7 Possible : 10 10 20 10 100 30 3 183 "( )" Indicates the assignment was not submitted. Key : 1) HW 9-11 5) TEST- Chap 1 2) HW 9-12 6) test 3) QUIZ 7) next 4) HW 9-14 Carlmont School Kingsfield's Per 7 Government Gradebook as of Fri Jan 4, 2002 Name Grade Cat 1 Cat 2 Cat 3 ------------------------------------------------------------------ Adams, John B 81.5 96.7 69.6 Adams, Quincy C 74.6 96.7 65.2 Cleveland, Grover C 75.4 100.0 60.9 Coolidge, Cal B 86.2 100.0 73.9 Eisenhower, Dwight A 94.6 100.0 78.3 Fillmore, Millard A 100.0 100.0 82.6 Ford, Jerry A 94.6 66.7 95.7 Grant, U. S. B 75.4 100.0 91.3 Harding, Warren B 79.2 100.0 87.0 Hoover, Herb A 93.8 100.0 100.0 Jackson, Andy A 96.2 100.0 100.0 Jefferson, Tommy B 83.1 100.0 95.7 Kennedy, Jack B 78.5 100.0 82.6 Lincoln, Abe B 80.8 100.0 91.3 Madison, Jim B 84.6 96.7 73.9 McKinley, Bill C 76.9 66.7 65.2 Monroe, John A 94.6 83.3 82.6 Pierce, Frank B 86.9 90.0 91.3 Polk, James C 75.4 93.3 78.3 Roosevelt, Frankie B 79.2 100.0 95.7 Roosevelt, Teddy B 78.5 100.0 87.0 Truman, Harry B 82.3 100.0 87.0 Tyler, John A 90.8 90.0 100.0 Washington, George C 83.8 66.7 73.9 Wilson, Woody B 78.5 100.0 87.0 Average : 84.2 93.9 83.8 Possible : 60 20 20 "( )" Indicates the assignment was not submitted. Category Key : 1) TEST 2) HW 3) OTHER
Digit Density
on Dec 27, 2001 at 19:22 UTC
by termix

What happens when you have too much time on your hands and you are getting drunk on vodka with a russian mathematician? Well, you get to proving that trancendental numbers are really digit sequences of uniform distribution over the 0 to 9 range.

Now that I am sober, I don't understand much of the reason behind all that, but this is a pretty nifty tool to print the relative density of digits in any numeric sequence. You can even use 'bc' or another arbitrary precision calculator to generate your large numbers.

How can we make this obfuscated?

Thanks japhy for your help. I've incorporated the smaller reader.

Actually looking at your array duplication, I can further take out the inner for loop.

XChat (IRC) XDCC script
on Dec 14, 2001 at 09:01 UTC
by mephit
This is a script for the XChat IRC client (which happens to use Perl as a scripting language, huzzah!) to handle xdcc stuff: sending files to others automatically as they're requested. The script is mostly subroutines that are completely independent of one another. It does What I Expect, and I know the IRC:: bits are right, but I'm wondering if the Perl can be made any more efficient somehow? I'd appreciate any feedback on this. The code is linked to below. This is my longest Perl program so far, and the first I'm showing to the general public, so please be gentle, OK? Thanks for any tips, folks.
Source code line numbering
on Nov 16, 2001 at 19:34 UTC
by Beatnik
Just put use Filter::NumberLines; at the top of your source file (below the shebang). It will automagically number your lines starting from the line after the use statement. I'll probably have it on CPAN at some point. At the moment I stashed up at perlmonk.org. Examples are included and online.
Update: removed that second my on $line (thanks blakem).
I don't know if it's too obvious but it's not a regular line numbering script. It's a source filter :)))
Dir Structure Print out
on Nov 14, 2001 at 02:14 UTC
by jclovs
I didn't like how Find:File Module worked for me and what I wanted to do so I created my own recursive program to print out a directory structure of my web directory, for new design purposes. So here it is hope someone finds it useful, and feel free to critque.
Games::QuizTaker
on Oct 12, 2001 at 03:41 UTC
by TStanley
Games::QuizTaker is the OO module implementation of my QuizTaker.pl script. I have also uploaded this module to CPAN, and as of 11 Oct 01, I am waiting for a response back.
UPDATE: It was approved on 11 Oct 01.
UPDATE: Version 1.02 released on 3 Nov 01
UPDATE: Version 1.03 released on 15 Nov 01
UPDATE: Version 1.04 released on 21 Nov 01
UPDATE: Version 1.06 released on 15 Dec 01
UPDATE: Version 1.24 released on 05 Feb 03
Perl module to handle simple logging
on Sep 25, 2001 at 09:21 UTC
by coolmichael
This module uses the DBI and DBD::CSV to handle all the file locking necessary for a simple logging facility.

I needed something like this for some of my CGI scripts. Appending to a table was a problem, as the file would sometimes loose some. I couldn't get flock to work, wanted to try writing object oriented perl.

Sample useage:

my $log=Logger->new("logfile", "/home/michael/logs"); open FILE, "myfile" or { $log->logger("something bad happened: $!"); die; }
I found it useful to have two log files open at the same time, one for fatal errors and one for warnings generated by bad input, or other non-fatal (recoverable) problems.

Please comment.

Calendar Array
on Sep 09, 2001 at 14:18 UTC
by rob_au
For a web application that I have been working on, I needed to display a small calendar with each day of the month lined up within day of the week columns. After searching the site, most answers to questions asking for something like this direct people to existing CPAN modules such as HTML::CalendarMonthSimple and PlotCalendar::Month. The problems with these solutions for my project is that I wanted to have more control over the HTML formatting output by the calendar routine.

The result is this snippet of code which returns a data structure which can be passed directly to HTML::Template for display as desired. eg.

<table border="0" cellpadding="2" cellspacing="0" width="140"> <tr> <td align="left" colspan="1" rowspan="1" valign="middle" width="20 +"> <font color="#000000" face="Tahoma, Verdana, Arial" size="2"><b> +S</b></font> </td> <td align="left" colspan="1" rowspan="1" valign="middle" width="20 +"> <font color="#000000" face="Tahoma, Verdana, Arial" size="2"><b> +M</b></font> </td> <td align="left" colspan="1" rowspan="1" valign="middle" width="20 +"> <font color="#000000" face="Tahoma, Verdana, Arial" size="2"><b> +T</b></font> </td> <td align="left" colspan="1" rowspan="1" valign="middle" width="20 +"> <font color="#000000" face="Tahoma, Verdana, Arial" size="2"><b> +W</b></font> </td> <td align="left" colspan="1" rowspan="1" valign="middle" width="20 +"> <font color="#000000" face="Tahoma, Verdana, Arial" size="2"><b> +T</b></font> </td> <td align="left" colspan="1" rowspan="1" valign="middle" width="20 +"> <font color="#000000" face="Tahoma, Verdana, Arial" size="2"><b> +F</b></font> </td> <td align="left" colspan="1" rowspan="1" valign="middle" width="20 +"> <font color="#000000" face="Tahoma, Verdana, Arial" size="2"><b> +S</b></font> </td> </tr> <tmpl_loop name="row"> <tr> <tmpl_loop name="day"><td align="left" colspan="1" rowspan="1" val +ign="middle" width="20"> <font color="#333333" face="Tahoma, Verdana, Arial" size="2"><tm +pl_var name="day"></font> </td> </tmpl_loop> </tr></tmpl_loop> </table>

In addition to this, for the project for which this was developed for, I passed an additional key that referenced a style dictated by the cascading style sheet for the HTML template. The flexibility of data set and template integration in this manner (in my opinion) surpasses that of some of the existing CPAN calendar modules - An example of this code in practice can be seen here.
Attribute::Protected
on Aug 28, 2001 at 10:30 UTC
by miyagawa
Attribute::Protected implements something like public / private / protected methods in C++ or Java. This module requires Attribute::Handlers.
Fibonacci Generator
on Aug 10, 2001 at 18:55 UTC
by sifukurt
Ok, so this is something from the Reinventing the Wheel Department. I was playing and ended up churning out a Fibonacci generator. I thought I'd share it here in the hopes that someone would find it useful. As always, comments welcome.

Update: Made code modifications as suggested.
Class::FlyweightWrapper
on Aug 10, 2001 at 08:05 UTC
by tilly
This is a proof of concept for how to automatically encapsulate one class with an implementation done in another one. It also implements what I mentioned could be done at Re (tilly) 3: Tie & Destroy, OOP. For more on this idea see the alternate implementation at Class::Flyweight - implement the flyweight pattern in OO perl.
ForkMe
on Aug 09, 2001 at 13:24 UTC
by jepri
A module that handles some of the hairier aspects of forking and communicating between processes.

It has OO methods to fork and handle IPC between the processes using TCP network sockets. Comes with excessive POD and examples. It may even be easy to use. The POD may be slightly out of sync since this is a rush release. /msg me if any troubles occur

Simple DBI Abstraction Class
on Aug 02, 2001 at 17:02 UTC
by rob_au
A while ago, I asked the collective wisdom of the Monastery regarding Metadata and DBI Abstraction in the context of utilising a simplier DBI interface for a medium-to-large web site I was working on. From this node, I received a number of very useful suggestions and recommendations via both follow-up nodes and the chatterbox, one of which almost led me to distraction with Tangram. After this experience I set about re-inventing the wheel to a certain extent, implementing a very basic abstraction class (which I later found had many similarities, in a basic form, to BingoX::Carbon to which princepawn directed me).
 
To this end, I present this very simple DBI abstraction class which may help others, who like myself, have need for a simple DBI abstraction class with a minimal learning curve (although if I had the time, I think I would have gone down the path of BingoX::Carbon). This module has been written to interface a PostgreSQL database and introduces new, connect, disconnect, param, select_array and select_hash abstraction methods which should be very easy to use for anyone familiar with the DBI interface. At this stage, the commit method has not been implemented, this abstraction class representing a read-only interface at this point in time.
 
In practical terms, this abstraction class allowed me to build a catalogue and shopping interface to a PostgreSQL database comprised of more than 5,000 products in under a fortnight of development time.
 
Self-extracting Perl archives
on Aug 01, 2001 at 19:58 UTC
by bikeNomad
Creates a self-extracting, uncompressed, Perl archive from the (possibly binary) files specified on the command line. Does not require any library modules for extraction. Will make directories as needed.

Does not yet handle cross-platform filenames or allow for translating paths from absolute to relative (though you can of course edit its output with another Perl program).

Note that these files will actually be at least 37% bigger than the input files because of the extractor and the uuencoding. But you can send binary with them without worrying about someone trashing them in a mail or FTP program.

Directory Hashing Algorithm
on Jul 31, 2001 at 20:02 UTC
by tadman
A simple function to distribute many files across as many directories, using an RC5 hash.
Monitor file require/use
on Jul 26, 2001 at 19:54 UTC
by bikeNomad
This little script will monitor the behavior of require/use in your script. It will run another Perl program and print out whatever files it's loading to STDERR.

Just run it on another program like this:

perl watchRequire.pl myProgram.pl arg1 arg2 2>required
Device::SMBus -- an interface for I2C and/or SMBus under Linux
on Jul 25, 2001 at 09:20 UTC
by bikeNomad
This lets you (if you're using Linux) access hardware connected via an I2C or SMBus interface, like (for instance) CPU temperature sensors. It uses Inline. You must have the lm_sensors library installed in your Linux system.
Tie::Static
on Jul 15, 2001 at 09:30 UTC
by tilly
This provides a way to produce static lexical variables in Perl without relying on the bug mentioned at Unusual Closure Behaviour. Ever since I pointed out this bug, I have not quite known what to do about people who think that it is a feature. Well I think it a good use of this, my 2000'th post, to provide an alternate solution for people who want static lexicals.

For an explanation of why the misfeature really is a bug, see my $foo if 0; is a bug.

To understand how to use this module, read the documentation.

Class::Flyweight - implement the flyweight pattern in OO perl
on Jul 08, 2001 at 04:08 UTC
by dkubb

Class::Flyweight is a module allows you to simply use the flyweight pattern in your modules. The major advantage to using this pattern is that the object data is not stored inside the blessed object itself. There is no way for a user of your module to access data in your object, unless you have provided the interface.

I am submitting this module for a code review, as I'm close to uploading it to CPAN. Before that I'd to get the monks' feedback and opinions before I take it to the next step.

In particular I am not sure of the following:

  • Do you think people will use it?
  • What about the method names? Something just doesn't feel comfortable about them. Especially clone(). Any naming suggestions?
  • Where should I beef up/trim down/improve the documentation?
  • Do you like the interface, and is it simple enough to not be limiting?
Filter::Interpolate
on Jul 06, 2001 at 07:39 UTC
by BrentDax
Filter::Interpolate allows you to put something like $(Foo) into a string, and have it interpolate the return value of Foo() in a scalar context. @(Foo) is used for list context. This code is a source filter; it depends on Filter::Simple, which depends on a lot of other things.

Please be gentle; it's very easy to outsmart this module. In particular, $(Foo('(')) will eat your entire program looking for a closing parenthesis (and then die gracefully), while $(Foo(')')) will give you a very strange error message about a missing curly or square bracket.

This module can also be used to force context--$() can be used instead of scalar(), and @() can be used instead of the mythical list(). In some cases @() may be the only way to get a list context.

I chose these semantics because they're pretty much identical to those proposed for Perl 6.

No XS required. POD is embedded. test.pl for this module is available upon request.

Instant message parser.
on Jun 26, 2001 at 00:35 UTC
by damian1301
This is just a short script I wrote to parse instant messages from AIM, AOL, CS, and Yahoo!. It basically just reads through a conversation file or you can paste the conversation directly in the script, and it will give you info on how many messages were sent by each person, the word count, and the letter count. A couple of friends found it pretty neat and I like it. As always I am open to all criticism but remember, I didn't try to make everything all complex on this; just a simple script. The output of the script is like so (example):
1056 words total, 6045 total characters Damian1301 has 175 IMs sent while Other_name has 154 IMs sent. There w +ere 329 IMs total
Round Robin Scheduling
on Jun 20, 2001 at 22:46 UTC
by modred
Given a list of teams creates a round robin schedule (a schedule where each team plays each of the other teams exactly once.)
Platform-independent Serial Port code
on Jun 16, 2001 at 02:41 UTC
by bikeNomad
This module makes it possible to use Perl programs that were written to use Win32::SerialPort or Device::SerialPort on the other kind of operating system without changing the source text. Just include the module and run your existing code:
perl -MAnySerialPort mySerialProgram.pl

It aliases the symbol table and provides a translating constructor.

Save it as AnySerialPort.pm somewhere on your Perl @INC path.

Module Dependencies
on Jun 05, 2001 at 19:12 UTC
by Brovnik
The script generates a database with information about the installed modules on your system.

They are stored in a mysql database.

A trivial CGI::Application can then be used to browse the database.

Will need Depend::Module to run, and Depend::Browse for the browser application, available here

Sample of the browser program running is Here<here

Short version of autoload
on Jun 03, 2001 at 01:18 UTC
by simon.proctor
I recently finished a large project involving a lot of OO prgramming. Tired of all the get and set methods I came up with the code below along with a co-worker in our lunch breaks. We did it more for fun than anything else so feel free to cut and paste it if you find it useful :P.

Our first attempts are commented out so you can see where we started off and what we ended up with.

If there are any bugs please let me know!
Inline::PERL
on May 31, 2001 at 20:25 UTC
by jmcnamara
Inline::PERL - Bring the power of PERL programming to your Perl programs.
Quick Perl coverage analyzer
on May 25, 2001 at 23:04 UTC
by bikeNomad
This uses the debugger to do a quick coverage analysis.

usage: run one script:

coverage script [ arg ... ] > listing.txt

or run multiple tests from a file of tests, one test per line.
coverage @file > listing.txt

output: subroutine summary and annotated listing on STDOUT, '-' signs show the lines that didn't get executed
Set::Range - conditional testing on sets
on Apr 23, 2001 at 23:36 UTC
by $code or die
This module lets you define a range of dates or numeric values and will return which set a given test value is a member of.

Personally, this will save me precious minutes by not having to do a lot of if .. then statements. It's not highly advanced or anything, just quite useful I think. e.g. want to do something depending on the value of x, but don't want the values to be hard-coded or difficult to change\add to?

Please let me know if you have any questions or suggestions - specifically, I'm looking for a nice way of removing that nasty eval statement... Also, do you think it's worth submitting this to CPAN, if so is Set::Range OK?

POD to follow...
(code) IP address - decimal to octal
on Apr 22, 2001 at 06:49 UTC
by ybiC
Convert a dotted-quad decimal IP address to it's dq octal form, and give a slightly rude retort if you don't know what constitutes a valid decimal dq.   Inspired by bruddaP's observation that pinging an IP address that's been leading-zero-padded results in ICMP echo request sent to unexpected host.

Thanks to Petruchio for the great code review below.   Thanks also to jeffa, chipmunk and buckaduck for number-range-matching help.   And to tye for further insight on calling subroutines.   Oh yeah, and to some guy named vroom.

Suggestions for improvement welcome and appreciated.

Updated:
2001-04-24
    Implemented most^W even more of Pfunk's suggestions.
    perldoc ipdec2oct.pl for details.

Loop::Watch
on Apr 17, 2001 at 06:51 UTC
by japhy
Thanks to some helpful feedback from my fellow monks, I offer Loop-Watch-0.01b. I'm not releasing it to CPAN until I have some testing results.
Help Name This Module
on Apr 14, 2001 at 00:01 UTC
by japhy
This code allows you to escape loops immediately when a condition is met. It is currently named "Ensure", but I know you can think of a better name.
QuizTaker.pl
on Mar 28, 2001 at 03:29 UTC
by TStanley
This program will read data from a CSV file and let you select how many
questions you wish to have on your test. It will then select random
questions for you to answer. This program doesn't yet support multiple
length questions(can't have multiple choice and true/false together)
The format for a question in the CSV file is as follows:

ID|Question|Choice|Choice|Choice|Choice|Answer

Where ID is a number relating to the question

**NOTE** I will be upgrading this program to include the use of modules, most likely Text::CSV_XS or tilly's Text::xSV module. I also would like to figure out how to include true/false questions as well.

**NOTE 2**Version 1.02 is now official. It uses tilly's Text::xSV module to parse the question file, which is pipe delimited.

**NOTE 3**Version 1.06 Now can support both true/false and multiple choice questions in the same question file.

**NOTE 4**Version 1.08 Now has a text-based menu interface, which means you can chose from a number of tests. I also wrote some POD for it as well
A (kinda) Circular Cache
on Mar 23, 2001 at 22:41 UTC
by mr.nick
A very simple, small, efficient (n) cache that maintains a limited set of items. Accessing an items moves it to the front of the cache which speeds location and refreshes it's age in the cache.
Math::Fleximal
on Mar 22, 2001 at 02:36 UTC
by tilly
This was inspired by irritation over Compact MD5 representation. If PHP has a solution, why doesn't Perl?

It is still kind of (OK) very rough.

My thanks to tye for a better name than I thought of.

As always the documentation is in the POD section.

X10 Timer script...
on Mar 19, 2001 at 08:42 UTC
by Clownburner
This is a simple Perl control script for the X10 Firecracker module (http://www.x10.com/firecracker/fc_x10_cm17a_br1.htm).

Useful for simple crontab timer applications. The Options are overly wordy to make for easy crontab reading later on.

Requires the ControlX10::CM17 module and Device::SerialPort module from CPAN. Serial port dependancy means that this code is probably not portable to Windows platforms without some modifications; other portability unknown.
SimpleMoney
on Mar 05, 2001 at 02:17 UTC
by Fingo
SimpleMoney is a quick and *simple* program to manage your funds. Currently it allows simple transaction, but I am planing on a reoccuring transaction feature. Other planed features include an ability to output a gnuplot readable file to draw graphs, the possibility of an optional tk gui, and (distant future) a sort of small scripting language to write more complex things (manage taxes anyone? ;) I want this program while containing many features to still not bog down the user and allow normal things without forcing the user to learn too much.
ForkBlock
on Feb 20, 2001 at 13:29 UTC
by BrentDax
This Perl module allows you to write forks like:
use ForkBlock; Fork { Parent { #parent code } Child { #child code } Error { #optional for handling non-recoverable errors } };

You use Fork if you want each process to terminate after its block, or DumbFork if you don't.

I'm not including the pod documentation, as it adds another hundred lines or so to the bottom of the script. If you want the source, including pod, e-mail me.

If nothing else, see it as a creative use of an anonymous hash.

Currently the only problem I have with it is that it doesn't croak if you forget the Parent or Child blocks, but I think that's pretty minor.

Emacs outline mode for Perl
on Feb 19, 2001 at 21:19 UTC
by clemburg
Ever tried outline-mode in an emacs? It works with Perl, too. Just put this code into your .emacs, or execute it from buffer *scratch*. Then do M-x perl-outline-mode after you opened the Perl code file. You can then expand and contract subroutines (with C-c @ C-t to contract all, C-c @ C-a to expand all, C-c @ C-d to contract a function, C-c @ C-s to expand it).
Code + Results to HTML
on Feb 25, 2001 at 02:16 UTC
by Anonymous Monk
This program reads all *.pl files in a given directory and then outputs the script followed by the results to an html file. Any suggestions for improvements, or added robustness would be much appreciated.
AbstractClass
on Dec 01, 2000 at 08:53 UTC
by tilly
This grew out of Interfaces in Perl?. This module provides a mechanism for creating what are called abstract base classes - classes that do not themselves define certain methods but impose an automatic check that they have been properly defined in derived classes.

Here is an example where Foo and Bar are two abstract base classes and Baz inherits from them. This was (not surprisingly) my test example. First Foo.pm, which requires a method called foo:

package Foo; use AbstractClass; @ABSTRACT_METHODS = qw(foo); sub foo {print "Subclasses are not allowed to use me\n";} 1;
Now Bar which is another abstract class inheriting from Foo, implementing foo, and requiring bar. I have shown the other way to declare an abstract method:
package Bar; use AbstractClass qw(bar); use Foo; @ISA = qw(Foo); sub foo {print "I am an allowable foo\n";} 1;
And finally, Baz.pm, a derived class inheriting from Bar:
use Bar; @ISA = qw(Bar); #sub foo {print "This is method foo\n";} sub bar {print "This is method bar\n";} 1;

UPDATE
Taking into account comments from Dominus (in a post which I think did not really deserve deletion) I have changed the name to AbstractClass, edited the documentation, and allowed abstract classes that do not define any new methods of their own. (This to allow classes that merely override a few methods.) I did not attempt to override bless, and won't pending some discussion. On the whole I don't much like overriding as a concept, and I am not sure that the gain is worth the pain.

Oh, and I added a version number. :-)

UPDATE 2
After some thought and an email to Damian I decided to implement a restriction to make it harder to create objects in an abstract class. While it would not be hard to make the check far stronger, doing so involves overriding bless everywhere, which is something I don't like philosophically. Also it would slow down the creation of objects from every constructor slightly. (As opposed to just slowing down constructors in abstract classes.)

UPDATE 3
Improved the check that subclasses overrode methods. Now you can usefully have an abstract class that inherits from a normal class and lists methods in that class which will need to be overridden (presumably because you have changed the implementation in some basic way). I am not sure that anyone would want to do so, but this issue was bugging me.

Continued Fractions
on Nov 16, 2000 at 15:45 UTC
by tilly
Everyone knows how to take a fraction and get a decimal number out. What is not so obvious is how to take the decimal and get a fraction back. Particularly with round-off error.

Well the trick is called continued fractions and the following program shows how you do it. In practice you just do enough iterations that you get down to round-off error and stop with that.

I suggest trying out a few fractions, and after that some expressions. Two fun expressions are

4 * atan2(1,1) (1 + 5**0.5)/2
The first will give you some well-known approximations of pi, and the second is the golden mean. The golden mean has the distinction of being the slowest continued fraction to converge. Its terms are also interesting to look at.

For more on the iterator techniques I used, I suggest this article.

Lat/Long distance calculator
on Nov 07, 2000 at 20:53 UTC
by jcwren
This code takes a latitude/longtitude pair and returns the distance and heading between them. As a practical (hah!) demonstration, it calculates how far your PM T-shirt has to travel to get from vroom to you (assuming you change the location, otherwise it's vroom to jcwren)
Versioned modules
on Oct 13, 2000 at 10:16 UTC
by tilly
This is my first pass at a solution to an interesting problem,, how to have modules that smoothly version themselves based on some criteria, which can have multiple versions loaded in parallel.

This version is pretty simple, the version that you get depends on an environment variable My test script is called test.pl and looks like this:

#! /usr/bin/perl # See comments in Versioning about warnings use strict; require versioned_module; tst(0); tst(1); tst(0); tst(1); sub tst { $ENV{IS_PROD} = shift; import versioned_module("report_version"); report_version(); }
The module it uses is versioned_module.pm:
package versioned_module; use Versioner; @ISA = qw(Versioner);
And this has two implementations, Prod/versioned_module.pvm and Devel/versioned_module.pvm that just happen to be the same:
use strict; use vars qw(@EXPORT_OK); @EXPORT_OK = qw(report_version); sub report_version { my $ver = __PACKAGE__; print "Got version $ver\n"; }
And when you run the test, you indeed get it switching versions back and forth depending on the environment variable.

This idea can, of course, be made more complex. :-)

UPDATE
A few improvements. It now works smoothly for OO modules as well without a custom import, see later post.

Matrix Multiplier
on Sep 09, 2000 at 07:35 UTC
by zdog
Being in Algebra II, my class is learning about matrices. Finding that multiplying matrices takes so long, I automated it using Perl with this script.

Suggestions are not only welcomed, but wanted!

Thanks to jcwren, jlp, BlaisePascal, and merlyn's Programming Perl for helping me out.

Substring Finding/Counting
on Aug 30, 2000 at 01:03 UTC
by Guildenstern
Originally written to find common substrings in raw packet data. Can take a file of strings and will count all occurrences of substrings. Can take parameters for smallest substring and number of minimum matches to show to speed it up. I only tested it with the characters 0-9 and A-Z, so the regex may need to be protected if you use different data.
Minimum command length matcher
on Aug 29, 2000 at 18:44 UTC
by jcwren
I write a fair number of programs that use interactive commands. I intensely dislike programs that require me to type more than the minimum number of characters to distinguish one command from another. I also dislike have to have special parameters that instruct the command interpeter what portion of the command is unique.

To that end, this snippet takes a hash of commands, keyed by the command name, and the user input, and finds the minimum match. Errors are no matches, or ambiguous matches, in which case an error message with the list of commands is returned. If no error, the full name of the hash is returned.
mybooks.pl
on Aug 09, 2000 at 05:41 UTC
by zdog
Script for managing one's collection of books.

Update: This was completely redone with a new interface and information stored in MySQL and the like.

Simple Locking
on Aug 08, 2000 at 23:03 UTC
by tilly
A simple module to implement locking. Check the documentation for flock on your system then make line 15 something appropriate and use it. (I am not kidding about the documentation - for instance on Linux you should not try to use flock on a directory mounted through NFS.) This is in essence a followup on the common mistakes that were brought up in RE: RE: Flock Subroutine.

The simplest and most common use is:

my $lock = Get Lock(lock_file => "foo.lock");
This blocks until you get that lock in your default locking directory. The contents of that file will by default say who currently has it locked.

Just drop the variable when you want to drop the lock. (What could be easier?) Look at the Get function to see what other useful options there are. For debugging or interactive use you may want to set $Lock::verbose to a true value.

Oops, a security hole. I made the following rather important edit:

--- lock1.pm Thu Aug 17 11:38:20 2000 +++ lock2.pm Thu Aug 17 11:41:04 2000 @@ -108,12 +108,15 @@ unless (-e $lockfile) { print STDERR "$lockfile not found! Creating\n"; local *FH; - open (FH, "> $lockfile") or confess("Cannot create $lockfile! $!" +); + open (FH, ">> $lockfile") or confess("Cannot create $lockfile! $! +"); close(FH); sleep 1; } open ($fh, "+< $lockfile") or confess("Cannot open $lockfile! $!"); + if (-l $fh) { + confess("Refusing to use symlink '$lockfile' as a lockfile."); + } if ($obj->{no_block}) { # test_only unless( flock ($fh, LOCK_EX | LOCK_NB)) {
GO Arena version 0.1a
on Jul 26, 2000 at 06:12 UTC
by gryng
Go Arena Version 0.1.1a This is a GO server and sample client. GO is an ancient asian game. Check out the nodes AI and GO and Go Arena released! for more information.

The point of this code is to allow programmers to test and develop their skill at writing AI programs. The go-arena.pl program allows two AI programs to connect over a network and play a game of GO. This will allow programmers to compete and interact with other programmers AI's inorder to learn better how to write their own.

Hopefully we will see good perl AI's out of this. But since the server is fully networked, you could write your AI in any language.

Update: Fixed a small bug in go-client.pl's arguement processing.

Listat
on May 27, 2000 at 02:27 UTC
by Anonymous Monk
Listat = List + Stat. Listat is a package to discover demographics of your mailing list. This package will be useful if you run a mailing list on the Internet. The package can be downloaded from http://wordsmith.org/anu/listat/
COBOL Killer
on May 03, 2000 at 20:19 UTC
by johncoswell

This code processes a formatted text file into COBOL code. Ick. 8^) Running from the Web frontend (http://johnbintz.dragonfire.net/cobolkiller), it accepts one parameter - "cobolcode", a TEXTAREA input from HTML. The report format is pasted into the TEXTAREA then sent to the script. An example report file would look like this:

01234567890123456789
COBOL REPORT  999999
--------------------
CODE       COST
XXXXXXXXXX 999999999

TOTAL     9999999999

The first line of the report file is ignored. I use it to line up and measure across columns. After that, the file is processed word by word in this way:

  • If the word has two or more capital Xs, the number of Xs is counted and a PIC clause for X(length) is returned
  • If the word has two or more 9s, the number of 9s is counted and a PIC clause for 9(length) is returned.
  • If neither of these two occur, the word is placed into a FILLER (kinda like a constant) and the FILLER is assigned a PIC clause of X(length)

I also wrote a version to work with CICS BMS macros, which are even more longwinded. Enjoy!

An Obfuscated ("The Perl Journal") Script
on Apr 27, 2000 at 01:54 UTC
by Marburg
Here is my entry to the last Perl Journal Obfuscation contest ... the "The Perl Journal" section. I hope it makes sense ... not! John.
nodebug.pl
on Apr 26, 2000 at 05:13 UTC
by Anonymous Monk

Do you get sick of sorting through all those conditional compilation statems of the form:


   #ifdef DEBUG
   /* C code here *.
   #endif

This short script will strip them out, making your C code more legible. Use input redirection to run your *.c files through this filtering program.

Copyright Writer
on Apr 25, 2000 at 19:59 UTC
by kayos

This writes COPYRIGHT files for me. Sometimes we give clients code with a very specific license. This lets me set the policies. It spits out the license statement on standard out.

Call it like this

mkcopyright "licensee"

I'll probably make changes to this code based on your comments, so check back later if you want a more flexible version

"Ate My Balls" Syntax Generator
on Apr 15, 2000 at 09:18 UTC
by Anonymous Monk
For those new to Perl, this script uses the ever-popular "Ate My Balls" joke to demonstrate simple concepts like variable assignments, while() loops, printing, simple array manipulation, and the use of Perl's rand() function.
Consider this Chapter 1 in your quest for Perl skillz. I will post more simple scripts like these as I continue to strengthen my "rabid sloth" style of Perl-Fu.
Getppt::(LongStd) replacement
on Mar 16, 2000 at 18:54 UTC
by Anonymous Monk
 usage:
use importopt (namespace=>"NS", options=>{opt1=>"type", opt2=>"type[]", opt3=>"=opt1"}); types: i (integer) /^[+-]?[0-9]+$/ f (float) /^[+-]?[0-9.]+(e[+-]?[0-9]+)?$/ s (string) /./ v (void) /^$/ new types can be defined by simply adding their regexp in %type. name=>"i[]" will define @NS::name holding all the values for all instances of --name. name=>"i" will define $NS::name holding the last given value if there are multiple instances (no error/warning given). name=>"=other" will make the option "name" an alias for the option "other". if "other" is defined to be an array (other=>"i[]"), then @NS::name will be an alias for @NS::other, else $NS::name will be an alias for $NS::other. your script won't be able to tell which one was used on the command line. options syntaxes (equivalent): -option[=value] --option[=value]
if value is ommited, 1 is assumed (for boolean options). all non-option @ARGV's will be copied to @NS::_args. if there are any errors (unknown option or invalid value), $NS::_err will be set to an error code and an error message will be displayed. error codes: 1: invalid value (didn't match regexp for type) 2: unknown option 3: reference to nonexistent option (aliasing)
Fax4Free
on Mar 10, 2000 at 14:51 UTC
by Dark1
Scipt uses the Net::SMTP module.. can be installed using PPM or VPM.
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (8)
As of 2014-09-18 10:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (111 votes), past polls