Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Miscellaneous

by vroom (His Eminence)
on May 26, 2000 at 01:08 UTC ( [id://14867]=sourcecodesection: print w/replies, xml ) Need Help??
Automatic ChangeLog Generation
on Apr 17, 2009 at 18:15 UTC
by DStaal

I hate maintaining a separate ChangeLog on my modules. I'd rather keep it in the module's POD. But that's not the Kwalitee way to do it, and I'd rather follow standard locations.

Or better yet, get Perl to let me write where I like, and recreate the standard file as desired...

This goes in a Build.PL script: Use $class->new instead of Module::Build->new to use.

Term::ReadLine::Perl::Bind
on Mar 19, 2009 at 02:33 UTC
by repellent
I have packaged up Term::ReadLine::Perl with bindkeys for most common terminals I have encountered and still use:
  • xterm
  • rxvt
  • linux - Linux native terminal
  • cons25 - FreeBSD native terminal
  • PuTTY

These bindkeys are tied to actions I personally would expect, such as:
  • Ctrl-Up arrow to search readline history.
  • Ctrl-Left arrow would move the readline cursor left word-by-word.
  • Shift-Right arrow removes the word to the right of the readline cursor, and stores it into the paste buffer.
  • Alt-Down arrow to slap down the paste buffer.
  • Home and End keys move the cursor to the beginning and end of the readline, respectively.
  • Delete key chews the character under the cursor, not the character before the cursor.
  • etc.

Usage

Instead of use Term::ReadLine::Perl;
just use Term::ReadLine::Perl::Bind;

Add this line to ~/.perldb to have the debugger's readline act the same way:
use Term::ReadLine::Perl::Bind;

Microsoft consoles are not supported. See the description on Win32::Console::ANSI.
schedule.pl
on Nov 30, 2008 at 20:21 UTC
by Minimiscience
This is a basic program for converting a specification of a weekly schedule (e.g., a class schedule) into a neat PostScript chart. Documenation is given as POD at the end of the file.
calcweek
on Aug 19, 2008 at 19:30 UTC
by sv87
This is a small Perl script to calculate the number of the week from any given date.
use Ensure -- module to spot undefined stuff
on Aug 05, 2008 at 18:53 UTC
by gone2015

I got really tired of being tripped up at run time by undefined subroutine references... particularly days after some change had broken a seldom used piece of code !

...this Ensure module picks up that sort of problem.

For more detail, see: Ensure Module.

I'm wondering if people would find this useful ?

CA::AutoSys::Jil module
on Apr 11, 2008 at 17:18 UTC
by runrig

Update: Doesn't seem to work anymore. E.g., latest version of autorep does not seem to have "-D" option. Instances of 'from_autosys' in code should probably be 'from_server'. I haven't used autosys for a while and am just getting back to it, so I may update this in the near future.

This is posted mainly because I said I would in response to a recent post. AutoSys is job scheduling software (like cron on steroids) from Computer Associates. This started out as just a JIL (AutoSys' Job Information Language) parser (to read files with multiple job definitions), and mutated into also getting job status and dependencies, and validating jil scripts. You'll need to configure the AUTOSERV hash...sorry this is mostly as is so things are not as generic as they could be. There is some overlap between this and what is already on CPAN (CA::AutoSys) but the existing CPAN module didn't have any JIL parsing, which is what I really needed in the beginning. If the output format of autorep or job_depends changes in past/future version of AutoSys, then something here will probably break.

And I would appreciate feedback on whether or not this works on other systems :-)

PgUp Home
on Mar 01, 2008 at 16:23 UTC
by halfcountplus
I have seen a few people wanting to use the F-keys, PgUp, End, (etc) in non-GUI apps. I once did too. Unfortunately this requires changing terminal modes with the poorly documented Term::ReadKey, but if you still want to go ahead, my short script will read the multicharacter KEYS and remember them with names you give them (eg, F7). These keys are identified by reducing the number of unique elements in 3,4, or 5 byte KEYS (remember, 1 character = 1 byte!) according to the chart at the beginning. You can hex these raw character values and use them in regex with \x.

So it can be done, but most people really won't want to ;) IMPORTANT: if you don't exit cleanly (w/ ENTER) the terminal probably won't return to normal mode, and your command line will now be unresponsive...

Update: I noticed recently there is a "Curses" module for perl on CPAN which probably makes this a lot simpler -- ie. i'm wrong, Term::ReadKey is neither the only nor the best option. However, Term::ReadLine::Gnu recognizes these multi-character escape sequences in "bind_keyseq".
ReturnDate.pm
on Sep 27, 2007 at 18:04 UTC
by tcf03
Returns the Earlier/Later Dates. I could not find anything on CPAN which provides this exact functionality.

upddate added a Sorted method to return a sorted list of dates
Creates an umbrello compliant xmi document from a set of classes
on Jun 14, 2007 at 15:06 UTC
by hanspoo
Create an acceptable representation of a perl object model in xmi. By default prints the xmi document in standard output, this can be overwriten with the parameter --out-file. It's based on an umbrello document retouched incrementally. Classes given in command line are fully loaded and are given different treatement than classes just referenced. This automatically sets a scope for recursion. Classes indicated on command line will ve eval'ed. May be you will need to set PERL5LIB. Cardinality is not considered yet. This script is a good starting point, it's dirty, but works.
Data type validation using regular expressions
on May 26, 2007 at 20:17 UTC
by Anonymous Monk
This is the first Perl script I ever wrote. Any input to make it better, or do differently (using some existing model, for example) highly appreciated.

The simple perl script proof of concept demonstrated here, performs data type validation on the provided data file. The script creates an output file with bad data attributes substituted by default values. The data type specification and default values are read from a specification file.

Usage example:

Consider sales_payment.dat file:

A|10.50|CC|2006/12/05|10:05:15 2|12A|Cash|2006/12/05|10:12:18 3|100|12 Un|2006/12/05|10:15:23 4|.85|A1|2006/12/05|10:18:00 5|-100|B2|2006/12/05|10:20:00 6||C|2006/12/05|10:22:00 7|100||2006/12/05|10:26:00 8|200|D|2006/02/31|10:32:00 9|2006/02/31|10:33:00 10|400|E|2006/03/40|30:35:00 11|400|F|1234|10:41:AA 10|300|G|2006/02/31|10:05:15
A specification file sales_payment.spec is created; the file contains metadata - data attribute name, attribute data type defined using regular expressions, and default data value that is used when the data file contains bad data - separated by commas (','):
transaction_number,^\d+$,-1 total_basket_amount,^[-+]?[0-9]*\.?[0-9]+$,0 payment_type,^\w$,_Unknown date,(19|20)\d\d[/](0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01]),1900/01/ +01 time,^([0-1][0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$,00:00:00
When we run data validation:
unix> perl validate_data_type.pl "sales_payment.spec" "sales_payment.d +at" "sales_payment_out.dat" "sales_payment.log" 50
...the output data file is created:
-1|10.50|CC|2006/12/05|10:05:15 2|0|Cash|2006/12/05|10:12:18 3|100|_Unknown|2006/12/05|10:15:23 4|.85|A1|2006/12/05|10:18:00 5|-100|B2|2006/12/05|10:20:00 6|0|C|2006/12/05|10:22:00 7|100|_Unknown|2006/12/05|10:26:00 8|200|D|2006/02/31|10:32:00 10|400|E|1900/01/01|00:00:00 11|400|F|1900/01/01|00:00:00 10|300|G|2006/02/31|10:05:15
...along with a log file:
Spec File> sales_payment.spec Data In File> sales_payment.dat Data Out File> sales_payment_out.dat Log File> sales_payment.log Max errors: 50 Error 1. Data type error on line: 1, attribute: 1 (transaction_number) Error 2. Data type error on line: 2, attribute: 2 (total_basket_amount +) Error 3. Data type error on line: 3, attribute: 3 (payment_type) Error 4. Data type error on line: 6, attribute: 2 (total_basket_amount +) Error 5. Data type error on line: 7, attribute: 3 (payment_type) Error 6. On the data line: 9, # attributes: 3, do not match # attribut +es in the file specification: 5 Error 7. Data type error on line: 10, attribute: 4 (date) Error 8. Data type error on line: 10, attribute: 5 (time) Error 9. Data type error on line: 11, attribute: 4 (date) Error 10. Data type error on line: 11, attribute: 5 (time) Process completed with: 10 errors Formatted documentation available at: <a href=http://www.dwoptimize.co +m/2007/05/data-type-validation-using-regular.html>www.dwoptimize.com< +/a>
Find doubly installed modules
on Apr 01, 2007 at 19:25 UTC
by Sixtease
Run this script from the perllib directory, where vendor_perl and site_perl directories reside. (in my case it's /usr/lib/perl5) The script will output the modules (.pm files) located in both subdirs. The branch (site_perl or vendor_perl) will be output for the older module (which you thus might want to remove).
Class::Basic
on Mar 19, 2007 at 19:41 UTC
by rlb3
This is an unholy combination of ideas and interface from Moose and ideas and code from Class::STD. Its mostly a toy but it does work. How well it works is a different story...
Huffman coding in pure Perl
on Mar 04, 2007 at 11:35 UTC
by vrk

This is a straightforward implementation of Huffman coding in pure Perl. The module is not intended to be used in real applications as such; rather, this is an educational module, which can be used to demonstrate how it can be done.

Included in the module documentation are a simple compression and an equally simple decompression program, which demonstrate how the module can be used in compressing text files.

UPDATE: use 5.008_000 instead of 5.000_008, of course. Thanks, geekphilosopher!

UPDATE 2: Removed the use line altogether. tye has good arguments why it's harmful.

Check if your site's been banned with Google
on Jan 08, 2007 at 13:15 UTC
by Alien
Script to check if your site has been banned from Google ... in an ideal world it would have checked for back links too ... but who knows :) ... maybe the next version !
Argdom.pm
on Nov 10, 2006 at 08:03 UTC
by revence27
Argdom.pm is good to help with managing arguments, in a very object-oriented way. Very extensible, because it uses high-level functions enough.
Latin Verb Conjugator
on Sep 22, 2006 at 01:58 UTC
by Minimiscience
As stated in the comments, this script will create a synopsis of a Latin verb in a specified person & number and will output the results as a LaTeX document. This script will work only for regular verbs and does not yet support deponents. You will need pdflatex and general knowledge of LaTeX accents to use it; without the former, you should edit the last four lines or so of the script. Without the latter, I pity you.
Subversion(SVN) pre-commit hook
on Jul 19, 2006 at 18:12 UTC
by runrig

I needed a Subversion pre-commit hook script to commit based on the name and contents of the file being committed. I found a python example, so I thought I'd try something similar in perl.

Warning: this seems to work, but I do not know if I've got the subclassing of the SVN::Delta::Editor methods correct (can't find good docs or examples). Advice is appreciated.

IP address - long to dottedquad to long
on Apr 28, 2006 at 19:47 UTC
by ruzam
Convert long integers to dotted quad notation string.
Convert dotted quad notation strings to long integer.

A couple of quick functions I've been using to convert IP addresses. I seem to be using these quite often.

Any and all comments/suggestions appreciated!

Thanks to jdporter and ikegami who have shown me a better way. The code here is credited to ikegami.
pythagorean triples
on Apr 23, 2006 at 20:01 UTC
by Pete_I
calculates pythagorean triples

explanation: a pythagorean triple is a set of non-zero integers that make the pythagorean theorem return true when they're plugged in.

3,4,5 is the first triple.
sqrt((3)**2 + (4)**2) = 25
sqrt(9 + 16) = 25
sqrt(25) == 5

I've got no idea what uses this could have, but I thought it was interesting.
it looked cleaner at the beginning, but map{} and for(a..b) had big memory problems.
If you find a use for it, i'd like to know. Enjoy :)
pod_to_html.pl
on Mar 18, 2006 at 11:46 UTC
by demerphq

This is a simple pod2html.pl emulator that wraps Pod::Simple::HTML. The Pod::Simple classes IMO aren't very well documented. Pod::Simple::HTML has almost nothing in the way of docs, and I havent seen a fully functional perl script that emulates the old TOMC version. So I'm hoping that this node might help fill the gap a little. I know some of you out there will have written almost the same thing so if you think yours is better or has something useful then please do post it.

I haven't tried to emulate the interface of the old pod2html.pl at all, but I might as time goes by.

Usage:

pod_to_html.pl [--css=FILESPEC] [--notoc] [PODFILE [HTMLFILE]] --css: If FILESPEC is 'auto' then tries to find the CSS based on the value of $^X. Currently 'auto' is only useful on Win32 ActiveState perls. If no value is provided and there exists a pod_to_html.css file in the same directory as the script is running from then it defaults to using that. --notoc: Turn off the Table Of Contents at the top. --notitlebars: Turn off the title header and footer lines If PODFILE is omitted reads from STDIN, if HTMLFILE is omitted writes to STDOUT.

FontPreview
on Dec 28, 2005 at 21:29 UTC
by qbxk
A first program using the experimental ServerApp module. Point this at a directory containing ttf files and it will use PerlMagick (Image Magick) to render provided text in a particular font. Useful when you have hundreds of fonts to "preview" for a particular word or phrase that needs just the right font - there is certainly much to be wanted feature-wise, this is an experiment and demonstration (you probably should use Firefox with this...)
Counting the Extensions of the Directory
on Dec 13, 2005 at 19:51 UTC
by Mago
Counting the Extensions of the Archives in Current Directory.
Fisher's Exact Test
on Aug 11, 2005 at 12:19 UTC
by tlm

See documentation with the code.

Note that the code computes factorials in only one place, the internal subroutine _single_term, which computes the hypergeometric probability function for a 2 x 2 contingency table (specified through its cell values, a, b, c, and d). Furthermore, the only dependance of the main routine (fishers_exact) on the Math::Pari module is through _single_term. If you prefer a library other than Math::Pari or don't like my implementation of _single_term, just replace it with your own. The rest of the code should work fine.

Also note that _single_term is called at most twice for every call to fishers_exact, so relegating this computation to a separate function doesn't significantly add to fishers_exact's overhead.

The computation of factorials attempts to use Math::Pari::factorial, and switches over to Gosper's approximation if that fails. Although, in principle, this maximizes the algorithm's accuracy, the performance cost may not justify this policy. For example, for 10_000!, the relative difference between the two methods is < 1e-10, but Gosper's is much faster:

Rate pari gospers pari 604/s -- -94% gospers 9657/s 1500% --
The cost/performance only gets worse for larger factorials.

On the other hand, if you find yourself working in this regime, ask yourself whether χ2 isn't more suited to your needs than than the FET.

Needless to say, I am providing this code "as is", without any expressed or implied warranties whatsoever. Use at your own risk.

mplayercrop
on Jul 29, 2005 at 15:50 UTC
by bumby
Autocrop for MPlayer
Blosxom Plug-in: authorcategory
on Jul 04, 2005 at 09:05 UTC
by goober99
Plugin for popular Perl weblog application, Blosxom, that allows you to link to all the articles written by the same author in the same way that you link to all the files in the same directory. The link $url/authors/name shows all the articles by "name." The link $url/authors creates a list of all the blog's authors.
MZT random number generator
on Jun 20, 2005 at 19:41 UTC
by js29a
Tiny module for high quality random number generation. Uses MZT method. The only thing you need to do is call r_univ() sub to get high-quality random number from 0.0 to 1.0.
jobs.perl.org watcher
on Jun 07, 2005 at 20:23 UTC
by diotalevi

This monitors jobs.perl.org (and eventually other sites) for postings of interest. There is separate code for watching the Minnesota Job Bank but since that's very specific, I left it out.

crontab entry to run once an hour, at 32 minutes past.

32 * * * * /home/.../bin/JobWatcher
Order your autobundle by dependency
on May 09, 2005 at 18:05 UTC
by cbrandtbuffalo
You can generate an autobundle from CPAN.pm easy enough, but it's in alphabetical order. This script uses some other modules to try to re-order the autobundle such that modules will be installed in the correct order so CPAN doesn't prompt you.

This is an initial step in my attempt to prepare for our perl upgrade and make it as easy as possible.

I'd really welcome some feedback if you try it out.

Update:Module::Dependency was a little cranky when I tried to install it (a few failing tests), so I forced it and it appears to work. I'll have to send something to the author.

Update:Turns out the topological sort in Graph sorts top-to-bottom, not bottom-to-top, so the list generated before was actually backwards. A simple reverse fixes the ordering.

weekly timesheet generator
on Mar 23, 2005 at 19:42 UTC
by multijoy
I'm not overly certain how useful this will be to others, but I couldn't find anything that did the same thing.
Basic concept is that it allows the user to time-stamp a weekly hours record, automagically creating each week's record.
Not much in the way of error checking, and I'm positive that the user interface could be less clunky. On the plus side, there 'aint that much to it.
The next trick will be to get it to email the timesheets as well!

Annotate XS code with notes on the perl API
on Nov 28, 2004 at 21:07 UTC
by diotalevi

Adds comments to your XS files with notes on the usage of the perl functions you've used. I wrote this to make noting which functions used implicit thread context or not, really easy. That and to not where a private API had been used inadvertantly.

This uses perl 5.8.6's embed.fnc file as a reference to perl's internal/public API. Perl's macros aren't listed there and so won't be covered by this utility.

mksc.pl
on Nov 10, 2004 at 20:20 UTC
by X-3mE
Extract a C shellcode from any binary program -- you must specify the function and the start/stop addresses
check syntax of perl code and pod in emacs
on Oct 11, 2004 at 14:13 UTC
by InfiniteLoop

If you use emacs, this function will check the syntax of your perl code and also run podchecker against it and display the result in a new buffer. You can call this function via the after-save-hook, and have the syntax checker run automatically. The function checks for CPerl mode.

Updated the code and the 'perlsyn' folder is shown only when there is a syntax error.(thanks to water)

Updated code to do a perl -wc (thanks to htoug)

norobotlog
on Sep 06, 2004 at 01:42 UTC
by quartertone
I always look at my Apache server log files from the command line. It always bothered me to see "GET /robots.txt" contaminating the logs. It was frustrating trying to visually determine which were crawlers and which were actual users. So I wrote this little utility, which filters out requests were made from IP addresses which grab "robots.txt". I suspect there are GUI log parsers that might provide the same functionality, but 1) i don't need something that heavy, 2) I like to code, 3) imageekwhaddyawant.
Dynamically Generating Mac OSX Terminal.app Colors
on Aug 28, 2004 at 17:15 UTC
by techy
I recently got a new iBook to play around with. My only disappointment was that the default Terminal.app uses the standard boring black text on white background. Inspired by the perlmonks node "to generate a set of well contrasted colors" as well as this article on macosxhints, I wrote a script to dynamically change the colors of Terminal.app on each login.

mask.pl_v0.1_alpha
on Jul 18, 2004 at 20:22 UTC
by X-3mE
This small script generates obfu's: you need a mask file (full of #'s), and your source perl file (without hash-bang). Simply call mask.pl source.pl mask.image and redirect the stdout somewhere, and here's your obfu.
Perl cheat sheet On-the-go
on Jun 26, 2004 at 11:59 UTC
by Aragorn
Juerd Waalboer's Perl 5 Cheat Sheet as an iPod Note.
DateTime::Calendar::Discordian
on Jun 09, 2004 at 23:43 UTC
by jaldhar
A module that implements the Discordian calendar like the ddate(1) program on Linux. Implements the DateTime API for compatability with other calendar modules.
Basic CPAN tester stats
on Jun 03, 2004 at 12:34 UTC
by LTjake

I was interested in some basic stats on how my CPAN testing client was doing. This little script will check the latest X posts (defaults to 50) to the perl.cpan.testers newsgroups for a particular author and display how many PASS/FAIL/UNKNOWN reports they have submitted.

a "screenshot":

C:\>perl tester-stats.pl cpansmoke@alternation.net Processing latest 50 items out of 142716 142716...Found 2 reports PASS: 002
Hash::AsObj
on Apr 06, 2004 at 17:51 UTC
by runrig
An experiment in AUTOLOAD and lvalue subs which resulted in a sort of combination of Hash::AsObject and Tie::SecureHash (update: actually more simply like Tie::Hash::FixedKeys or Hash::Util::lockkeys). The hash is 'secure' as long as you only access it as an object using methods, but you are free to add keys when directly accessing it as a hash ref. In the interest of keeping it simple, I'm not going to worry about handling keys like 'isa', 'can', 'AUTOLOAD', 'DESTROY', or '*::*'. And this definitely breaks can().

Updated/fixed code so that lvalue methods work better.(see reply node)

Kings Dream
on Mar 01, 2004 at 18:18 UTC
by snowsmann
This is an implementation of the "King's Dream" found in the book Chaos in Wonderland by Clifford A. Pickover. It is a complex algorithm to realize some aspects of chaos theory. It creates some very beautiful pictures and this program has three of the infinite possibilites of cool images produced. My program also allows the user to select the resolution and how many iterations to repeat the set of equations while drawing. Any comments or suggestions would be welcome. Anyone think of a good way to use colors to make this look even cooler?
Update: btw, for all who either cant get image::magick to install or are too lazy to do it, here are some images produced by this program the default image produced big(7.45 meg) image, 10000x10000 with 1.5 million iterations a not so good attempt at color scemes(in case you were wondering, i am in fact somewhat color blind) i would like any suggestion on a better way to color-enable this program
Additional ctags' Perl support
on Feb 03, 2004 at 05:13 UTC
by dmitri
This patch adds several nice features to ctags' support of Perl. More are likely to come. Summary: New feature support in perl parser:
  - support for 'use constant ABC => "xyz";' construct (ABC
    tag is created);
  - support for label constructs:
      EXIT:
    will produce a tag for EXIT;
  - support for full (package name + name) tags for
    constants and subroutines:
      package ABC::XYZ;
      sub hello {         # will create tags
                          # 'ABC::XYZ::hello'
                          # and 'hello', in case hello is
                          # called in the first way.
      }

Update: Now patch is provided instead of a link to it.

Update 2: This node 444294 provides a newer patch against ctags 5.5.4.

matrix determinants
on Nov 17, 2003 at 03:30 UTC
by ysth
A friend was reviewing precalculus (in preparation to return to school after a decade off and place into a real math class), and was working through some maxtrix determinant problems. I wrote this to help her catch arithmetic errors when calculating minors of a larger matrix. I only spent about 15 minutes, so its kind of rough, but I'm pretty satisfied, especially with how the input code handles errors.
Regexp::Approx - Use fuzzy regular expressions
on Nov 12, 2003 at 06:09 UTC
by diotalevi

This module allows you to use any of String::Approx's functions from within a regular expression. It also provides a convenience function `fuzzy_qr` which provides a regex fragment that works like an inline `scalar amatch( $pattern, $test )` expression.

use Regexp::Approx 'fuzzy_qr'; use re 'eval'; $r = qr/((?:@{[fuzzy_qr('APT')]}\s)?\w+\d)$/; $apt = ( "5678 DELAWARE AVENUE AOT 123" =~ $r )[0]; print "\$apt=$apt\n";
Notes::OLE - Lotus Domino via Win32::OLE
on Oct 31, 2003 at 21:50 UTC
by diotalevi
This module makes writing perl for Lotus Domino easy by precreating your session object and providing some utility functions for enumerating available servers and traversing document collections.
start
on Oct 14, 2003 at 07:52 UTC
by #include
I've always liked the Windows "start" commandline utility. It opens any file passed to it with the appropriate program. For example, issuing "start mysong.mp3" will open "mysong.mp3" with the default MP3 player, etc. "start" is my attempt to write a similar utility for *NIX systems. "start" uses the GNU utility "file" to determine a file's MIME type, and looks in a local flatfile database for a "command association" (in other words, the program that that MIME type is assigned to). If there isn't an entry present, it asks the user for a program to associate with that MIME type. "start" can be run in commandline mode, or (if you start it with the "-g" flag and no other arguments) it can be used with a Tk GUI. POD documentation has been included. Heavily commented.

REQUIREMENTS: GNU utility file, Perl, Tk

Devel::SummarizedWarnings
on Oct 09, 2003 at 23:37 UTC
by diotalevi

This traps warnings and prints them summarized instead of in masses. Instead of getting 3542 messages stating "Use of uninitialized value ..." at various lines you get only a few and they list all the lines it happened at and how many times.

Updated: The warnings are now displayed in the order they were first seen (they used to be in ascibetical order) and the warning messages are slightly more succinct. Instead of "on line 5 (11 times), line 8" now "on line 5 (x11) and 8".

XML::Maker
on Oct 05, 2003 at 21:58 UTC
by vadim_t
This is some code I wrote a while ago for generating XML. I hadn't heard of XML::Writer yet. Now that I tried XML::Writer I saw that it's missing a few features I want, and due to how it's written it'd be hard to add them. So I undusted this module, updated it, and added POD documentation.
Convert Gregorian/Islamic Date
on Aug 21, 2003 at 15:04 UTC
by projekt21
My wife needed to know some islamic festival dates, so I wrote a conversion module (stealing code from KDE). It still misses features like getting the day of week and others. If anybody is interested I will expand it and/or implement it into Date::Convert as a subclass. Please give me some comments.
Plaintext monthly journal generator
on Jul 20, 2003 at 00:31 UTC
by Dragonfly
I've used this script under both Win32 and OpenBSD to generate a plain-text file that I use for keeping a little journal of my thoughts.

I wrote it a long time ago (it's written in baby Perl) but have been using it monthly to make my journals, which are then really easy to edit and archive. I like keeping them in plain text format because then the entries are easy to cut and paste into other applications (emails, HTML forms, word processors, etc) without having to start a gigantic program or be online, etc.

I also like it because it simply writes a date for each day of the current month, like "Monday, July 14, 2003", with a few line breaks thrown in. That way, I can write down what I worked on that day, keep little notes or code snippets, lyrics, and so forth, and easily go back and review my month. And cross-platform date handling is a little trickier than I had initially expected, so I learned some things writing it, too.

Anyway, I know it isn't fancy, but since I use it every month, I figure somebody else out there might.

Simple "showkey" in Perl
on Jul 05, 2003 at 21:02 UTC
by Mr_Person

While working on a project, I was trying to find a way to get the status of numlock and preferably be able to tell when it was pressed. belg4mit pointed out that it was possible to get the scan code for Numlock using the showkey program. I took a look at the showkey source and found out that it does several things to the keyboard mode that allows it to capture raw scan codes. The first part is pretty much the same as saying ReadMode 4; with Term::ReadKey, but the last part I hadn't seen before and it set the keyboard to "MEDIUMRAW" mode. On closer inspection, it used an ioctl call to the current filehandle with some constants from the kd.h header file in the Linux kernel sources. It then does a bitwise AND with each character and 0x7f to get the scancode and also tests if a bitwise AND with 0x80 is true in which case the key was released, false it was pressed.

This program just uses the hard coded values taken from the kd.h file instead of including it like showkey does. There's probably a better way to do this, but I didn't know of one that would work easily. It also doesn't include as much error checking as showkey to make sure your keyboard gets back to how it should be or as many options for output.

Tablature Generator
on Jun 26, 2003 at 19:27 UTC
by crashnburn
This is a script that generates guitar tablatures from a file. It spares you the work of drawing the tablature by hand.
Lotus Notes address book export browser
on Jun 10, 2003 at 05:55 UTC
by greenFox
As I spend most of my time in cygwin with an xterm to some unix host or another swapping back to Notes for a phone number seemed like a pain :) I added the number matching facility to help auditing my phone bill.
Module 'Date'
on Jun 04, 2003 at 06:35 UTC
by nite_man
Update: This module is an OO Perl interface for management of dates and provides wide enough functionality for this. I developed this module with my colleague and it is very useful for us. I hope that this module will be useful for someone at list.
Ed2K Link Maker
on Jun 03, 2003 at 03:56 UTC
by #include
A small script that makes Ed2K links for use with the eDonkey P2P network. Just pass the script a filename as an argument, and the Ed2K link is printed to STDOUT. Uses Digest::MD5.

MASSIVE UPDATE: I pretty much rewrote the script from scratch and added a bunch of stuff: the ability to be used as both a commandline tool AND a GUI tool, the ability to hash multiple files, and some minor bugfixes. If you want to use the GUI, you must have Tk installed.
Seen.pm
on May 07, 2003 at 17:19 UTC
by defyance
A module to use with perl IRC bots to provide drop in "Seen" functionality. Basically it allows the bot to tell you the last seen action from a particular IRC user. At this point, you have to tell it which events to log, I consider this a feature. MySQL logging functionality is being considered. For now it uses a simple log file and a hash to do the logging. Some may find it pointless, some may find it interesting. I'm mainly looking for input on how to improve my code.
Simple Greeter
on Apr 30, 2003 at 15:14 UTC
by harley_frog
This is my very first "original" Perl script, inspired by "Hello World" only more intelligent. I've just started reading the Llama book and applied some of my new found knowledge to this script. Working towards a future version that will automatically input the current user's name, thus eliminating the prompt. Also working on a 12-hour clock version.

Check for updated code below.

B::Deobfuscate - Deobfuscates symbol names
on Mar 20, 2003 at 15:23 UTC
by diotalevi

B::Deobfuscate is a backend module for the Perl compiler that generates perl source code, based on the internal compiled structure that perl itself creates after parsing a program. It adds symbol renaming functions to the B::Deparse module. An obfuscated program is already parsed and interpreted correctly by the B::Deparse program. Unfortunately, if the obfuscation involved variable renaming then the resulting program also has obfuscated symbols.

This module takes the last step and fixes names like $z5223ed336 to be a word from a dictionary. While the name still isn't meaningful it is at least easier to distinguish and read.

LDAP Server TLS tester
on Jan 17, 2003 at 19:05 UTC
by beernuts
This is a chunk of code (test_tls.pl) that can be used to test LDAP servers for their ability to do TLS. It's culled from a bigger script I use to test an in-house LDAP proxy for proper installation of the script (it's in perl too) as well as the required modules.

usage:

'test_tls.pl -q' for details

Math::SnapTo
on Dec 25, 2002 at 15:14 UTC
by tachyon

The Math::SnapTo module provides several methods to snap numeric values to desired values according to various criteria.

Update

Further research has revealed that this functionality is already available in Math::Round with the nearest() function and Math::SigFigs so this module has been slated for deletion :-(

The Definitive Unit Conversion Script
on Dec 13, 2002 at 15:28 UTC
by Aristotle

Just what you'd expect from the title. :-)

New conversions are very easy to add; add a new row to the table, containing the source and destination unit and the factor to multiply by to get one from the other. If it's not a simple factor, add an array with two subrefs, one to convert from source to destination unit and another to convert backwards.

It will automatically keep applying conversions and reverse conversions to all the results it generates until it has calculated all related units from any given one.

Run it and it will tell you how to use it.

RegexLab (a wxPerl version)
on Dec 01, 2002 at 14:15 UTC
by PodMaster
Run it as a standalone app, or embed it easily into any wxPerl application, so you can test and devise regular expressions without starting a separate shell.

Install YAPE::Regex::Explain to gain insight into what you wrote. Perfect for newbies and experienced users.

http://crazyinsomniac.perlmonk.org/perl/RegexLab/

PseudoDBM
on Nov 25, 2002 at 14:07 UTC
by fruiture

PseudoDBM - pure Perl Hash-tie()ing to fixed-length-record-text-files

Well, that's all. I think it may be usefull sometimes to have a Pseudo-DBM you can use everywhere and that's readable(for control).

EDI Store and Forward System
on Oct 02, 2002 at 03:37 UTC
by diskcrash
This code is the main part of an X12 EDI (Electronic Data Interchange) store and forward system. It parses aggregate files of EDI transactions for ISA header information and forwards the EDI transaction on to an output directory. From there you can move the data to an EDI forwarder by FTP or other tools. It won't win ANY golf contests but was written to be maintainable.
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.
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.
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).
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/
Automatic ChangeLog Generation
on Apr 17, 2009 at 18:15 UTC
by DStaal

I hate maintaining a separate ChangeLog on my modules. I'd rather keep it in the module's POD. But that's not the Kwalitee way to do it, and I'd rather follow standard locations.

Or better yet, get Perl to let me write where I like, and recreate the standard file as desired...

This goes in a Build.PL script: Use $class->new instead of Module::Build->new to use.

Term::ReadLine::Perl::Bind
on Mar 19, 2009 at 02:33 UTC
by repellent
I have packaged up Term::ReadLine::Perl with bindkeys for most common terminals I have encountered and still use:
  • xterm
  • rxvt
  • linux - Linux native terminal
  • cons25 - FreeBSD native terminal
  • PuTTY

These bindkeys are tied to actions I personally would expect, such as:
  • Ctrl-Up arrow to search readline history.
  • Ctrl-Left arrow would move the readline cursor left word-by-word.
  • Shift-Right arrow removes the word to the right of the readline cursor, and stores it into the paste buffer.
  • Alt-Down arrow to slap down the paste buffer.
  • Home and End keys move the cursor to the beginning and end of the readline, respectively.
  • Delete key chews the character under the cursor, not the character before the cursor.
  • etc.

Usage

Instead of use Term::ReadLine::Perl;
just use Term::ReadLine::Perl::Bind;

Add this line to ~/.perldb to have the debugger's readline act the same way:
use Term::ReadLine::Perl::Bind;

Microsoft consoles are not supported. See the description on Win32::Console::ANSI.
schedule.pl
on Nov 30, 2008 at 20:21 UTC
by Minimiscience
This is a basic program for converting a specification of a weekly schedule (e.g., a class schedule) into a neat PostScript chart. Documenation is given as POD at the end of the file.
calcweek
on Aug 19, 2008 at 19:30 UTC
by sv87
This is a small Perl script to calculate the number of the week from any given date.
use Ensure -- module to spot undefined stuff
on Aug 05, 2008 at 18:53 UTC
by gone2015

I got really tired of being tripped up at run time by undefined subroutine references... particularly days after some change had broken a seldom used piece of code !

...this Ensure module picks up that sort of problem.

For more detail, see: Ensure Module.

I'm wondering if people would find this useful ?

CA::AutoSys::Jil module
on Apr 11, 2008 at 17:18 UTC
by runrig

Update: Doesn't seem to work anymore. E.g., latest version of autorep does not seem to have "-D" option. Instances of 'from_autosys' in code should probably be 'from_server'. I haven't used autosys for a while and am just getting back to it, so I may update this in the near future.

This is posted mainly because I said I would in response to a recent post. AutoSys is job scheduling software (like cron on steroids) from Computer Associates. This started out as just a JIL (AutoSys' Job Information Language) parser (to read files with multiple job definitions), and mutated into also getting job status and dependencies, and validating jil scripts. You'll need to configure the AUTOSERV hash...sorry this is mostly as is so things are not as generic as they could be. There is some overlap between this and what is already on CPAN (CA::AutoSys) but the existing CPAN module didn't have any JIL parsing, which is what I really needed in the beginning. If the output format of autorep or job_depends changes in past/future version of AutoSys, then something here will probably break.

And I would appreciate feedback on whether or not this works on other systems :-)

PgUp Home
on Mar 01, 2008 at 16:23 UTC
by halfcountplus
I have seen a few people wanting to use the F-keys, PgUp, End, (etc) in non-GUI apps. I once did too. Unfortunately this requires changing terminal modes with the poorly documented Term::ReadKey, but if you still want to go ahead, my short script will read the multicharacter KEYS and remember them with names you give them (eg, F7). These keys are identified by reducing the number of unique elements in 3,4, or 5 byte KEYS (remember, 1 character = 1 byte!) according to the chart at the beginning. You can hex these raw character values and use them in regex with \x.

So it can be done, but most people really won't want to ;) IMPORTANT: if you don't exit cleanly (w/ ENTER) the terminal probably won't return to normal mode, and your command line will now be unresponsive...

Update: I noticed recently there is a "Curses" module for perl on CPAN which probably makes this a lot simpler -- ie. i'm wrong, Term::ReadKey is neither the only nor the best option. However, Term::ReadLine::Gnu recognizes these multi-character escape sequences in "bind_keyseq".
ReturnDate.pm
on Sep 27, 2007 at 18:04 UTC
by tcf03
Returns the Earlier/Later Dates. I could not find anything on CPAN which provides this exact functionality.

upddate added a Sorted method to return a sorted list of dates
Creates an umbrello compliant xmi document from a set of classes
on Jun 14, 2007 at 15:06 UTC
by hanspoo
Create an acceptable representation of a perl object model in xmi. By default prints the xmi document in standard output, this can be overwriten with the parameter --out-file. It's based on an umbrello document retouched incrementally. Classes given in command line are fully loaded and are given different treatement than classes just referenced. This automatically sets a scope for recursion. Classes indicated on command line will ve eval'ed. May be you will need to set PERL5LIB. Cardinality is not considered yet. This script is a good starting point, it's dirty, but works.
Data type validation using regular expressions
on May 26, 2007 at 20:17 UTC
by Anonymous Monk
This is the first Perl script I ever wrote. Any input to make it better, or do differently (using some existing model, for example) highly appreciated.

The simple perl script proof of concept demonstrated here, performs data type validation on the provided data file. The script creates an output file with bad data attributes substituted by default values. The data type specification and default values are read from a specification file.

Usage example:

Consider sales_payment.dat file:

A|10.50|CC|2006/12/05|10:05:15 2|12A|Cash|2006/12/05|10:12:18 3|100|12 Un|2006/12/05|10:15:23 4|.85|A1|2006/12/05|10:18:00 5|-100|B2|2006/12/05|10:20:00 6||C|2006/12/05|10:22:00 7|100||2006/12/05|10:26:00 8|200|D|2006/02/31|10:32:00 9|2006/02/31|10:33:00 10|400|E|2006/03/40|30:35:00 11|400|F|1234|10:41:AA 10|300|G|2006/02/31|10:05:15
A specification file sales_payment.spec is created; the file contains metadata - data attribute name, attribute data type defined using regular expressions, and default data value that is used when the data file contains bad data - separated by commas (','):
transaction_number,^\d+$,-1 total_basket_amount,^[-+]?[0-9]*\.?[0-9]+$,0 payment_type,^\w$,_Unknown date,(19|20)\d\d[/](0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01]),1900/01/ +01 time,^([0-1][0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$,00:00:00
When we run data validation:
unix> perl validate_data_type.pl "sales_payment.spec" "sales_payment.d +at" "sales_payment_out.dat" "sales_payment.log" 50
...the output data file is created:
-1|10.50|CC|2006/12/05|10:05:15 2|0|Cash|2006/12/05|10:12:18 3|100|_Unknown|2006/12/05|10:15:23 4|.85|A1|2006/12/05|10:18:00 5|-100|B2|2006/12/05|10:20:00 6|0|C|2006/12/05|10:22:00 7|100|_Unknown|2006/12/05|10:26:00 8|200|D|2006/02/31|10:32:00 10|400|E|1900/01/01|00:00:00 11|400|F|1900/01/01|00:00:00 10|300|G|2006/02/31|10:05:15
...along with a log file:
Spec File> sales_payment.spec Data In File> sales_payment.dat Data Out File> sales_payment_out.dat Log File> sales_payment.log Max errors: 50 Error 1. Data type error on line: 1, attribute: 1 (transaction_number) Error 2. Data type error on line: 2, attribute: 2 (total_basket_amount +) Error 3. Data type error on line: 3, attribute: 3 (payment_type) Error 4. Data type error on line: 6, attribute: 2 (total_basket_amount +) Error 5. Data type error on line: 7, attribute: 3 (payment_type) Error 6. On the data line: 9, # attributes: 3, do not match # attribut +es in the file specification: 5 Error 7. Data type error on line: 10, attribute: 4 (date) Error 8. Data type error on line: 10, attribute: 5 (time) Error 9. Data type error on line: 11, attribute: 4 (date) Error 10. Data type error on line: 11, attribute: 5 (time) Process completed with: 10 errors Formatted documentation available at: <a href=http://www.dwoptimize.co +m/2007/05/data-type-validation-using-regular.html>www.dwoptimize.com< +/a>
Find doubly installed modules
on Apr 01, 2007 at 19:25 UTC
by Sixtease
Run this script from the perllib directory, where vendor_perl and site_perl directories reside. (in my case it's /usr/lib/perl5) The script will output the modules (.pm files) located in both subdirs. The branch (site_perl or vendor_perl) will be output for the older module (which you thus might want to remove).
Class::Basic
on Mar 19, 2007 at 19:41 UTC
by rlb3
This is an unholy combination of ideas and interface from Moose and ideas and code from Class::STD. Its mostly a toy but it does work. How well it works is a different story...
Huffman coding in pure Perl
on Mar 04, 2007 at 11:35 UTC
by vrk

This is a straightforward implementation of Huffman coding in pure Perl. The module is not intended to be used in real applications as such; rather, this is an educational module, which can be used to demonstrate how it can be done.

Included in the module documentation are a simple compression and an equally simple decompression program, which demonstrate how the module can be used in compressing text files.

UPDATE: use 5.008_000 instead of 5.000_008, of course. Thanks, geekphilosopher!

UPDATE 2: Removed the use line altogether. tye has good arguments why it's harmful.

Check if your site's been banned with Google
on Jan 08, 2007 at 13:15 UTC
by Alien
Script to check if your site has been banned from Google ... in an ideal world it would have checked for back links too ... but who knows :) ... maybe the next version !
Argdom.pm
on Nov 10, 2006 at 08:03 UTC
by revence27
Argdom.pm is good to help with managing arguments, in a very object-oriented way. Very extensible, because it uses high-level functions enough.
Latin Verb Conjugator
on Sep 22, 2006 at 01:58 UTC
by Minimiscience
As stated in the comments, this script will create a synopsis of a Latin verb in a specified person & number and will output the results as a LaTeX document. This script will work only for regular verbs and does not yet support deponents. You will need pdflatex and general knowledge of LaTeX accents to use it; without the former, you should edit the last four lines or so of the script. Without the latter, I pity you.
Subversion(SVN) pre-commit hook
on Jul 19, 2006 at 18:12 UTC
by runrig

I needed a Subversion pre-commit hook script to commit based on the name and contents of the file being committed. I found a python example, so I thought I'd try something similar in perl.

Warning: this seems to work, but I do not know if I've got the subclassing of the SVN::Delta::Editor methods correct (can't find good docs or examples). Advice is appreciated.

IP address - long to dottedquad to long
on Apr 28, 2006 at 19:47 UTC
by ruzam
Convert long integers to dotted quad notation string.
Convert dotted quad notation strings to long integer.

A couple of quick functions I've been using to convert IP addresses. I seem to be using these quite often.

Any and all comments/suggestions appreciated!

Thanks to jdporter and ikegami who have shown me a better way. The code here is credited to ikegami.
pythagorean triples
on Apr 23, 2006 at 20:01 UTC
by Pete_I
calculates pythagorean triples

explanation: a pythagorean triple is a set of non-zero integers that make the pythagorean theorem return true when they're plugged in.

3,4,5 is the first triple.
sqrt((3)**2 + (4)**2) = 25
sqrt(9 + 16) = 25
sqrt(25) == 5

I've got no idea what uses this could have, but I thought it was interesting.
it looked cleaner at the beginning, but map{} and for(a..b) had big memory problems.
If you find a use for it, i'd like to know. Enjoy :)
pod_to_html.pl
on Mar 18, 2006 at 11:46 UTC
by demerphq

This is a simple pod2html.pl emulator that wraps Pod::Simple::HTML. The Pod::Simple classes IMO aren't very well documented. Pod::Simple::HTML has almost nothing in the way of docs, and I havent seen a fully functional perl script that emulates the old TOMC version. So I'm hoping that this node might help fill the gap a little. I know some of you out there will have written almost the same thing so if you think yours is better or has something useful then please do post it.

I haven't tried to emulate the interface of the old pod2html.pl at all, but I might as time goes by.

Usage:

pod_to_html.pl [--css=FILESPEC] [--notoc] [PODFILE [HTMLFILE]] --css: If FILESPEC is 'auto' then tries to find the CSS based on the value of $^X. Currently 'auto' is only useful on Win32 ActiveState perls. If no value is provided and there exists a pod_to_html.css file in the same directory as the script is running from then it defaults to using that. --notoc: Turn off the Table Of Contents at the top. --notitlebars: Turn off the title header and footer lines If PODFILE is omitted reads from STDIN, if HTMLFILE is omitted writes to STDOUT.

FontPreview
on Dec 28, 2005 at 21:29 UTC
by qbxk
A first program using the experimental ServerApp module. Point this at a directory containing ttf files and it will use PerlMagick (Image Magick) to render provided text in a particular font. Useful when you have hundreds of fonts to "preview" for a particular word or phrase that needs just the right font - there is certainly much to be wanted feature-wise, this is an experiment and demonstration (you probably should use Firefox with this...)
Counting the Extensions of the Directory
on Dec 13, 2005 at 19:51 UTC
by Mago
Counting the Extensions of the Archives in Current Directory.
Fisher's Exact Test
on Aug 11, 2005 at 12:19 UTC
by tlm

See documentation with the code.

Note that the code computes factorials in only one place, the internal subroutine _single_term, which computes the hypergeometric probability function for a 2 x 2 contingency table (specified through its cell values, a, b, c, and d). Furthermore, the only dependance of the main routine (fishers_exact) on the Math::Pari module is through _single_term. If you prefer a library other than Math::Pari or don't like my implementation of _single_term, just replace it with your own. The rest of the code should work fine.

Also note that _single_term is called at most twice for every call to fishers_exact, so relegating this computation to a separate function doesn't significantly add to fishers_exact's overhead.

The computation of factorials attempts to use Math::Pari::factorial, and switches over to Gosper's approximation if that fails. Although, in principle, this maximizes the algorithm's accuracy, the performance cost may not justify this policy. For example, for 10_000!, the relative difference between the two methods is < 1e-10, but Gosper's is much faster:

Rate pari gospers pari 604/s -- -94% gospers 9657/s 1500% --
The cost/performance only gets worse for larger factorials.

On the other hand, if you find yourself working in this regime, ask yourself whether χ2 isn't more suited to your needs than than the FET.

Needless to say, I am providing this code "as is", without any expressed or implied warranties whatsoever. Use at your own risk.

mplayercrop
on Jul 29, 2005 at 15:50 UTC
by bumby
Autocrop for MPlayer
Blosxom Plug-in: authorcategory
on Jul 04, 2005 at 09:05 UTC
by goober99
Plugin for popular Perl weblog application, Blosxom, that allows you to link to all the articles written by the same author in the same way that you link to all the files in the same directory. The link $url/authors/name shows all the articles by "name." The link $url/authors creates a list of all the blog's authors.
MZT random number generator
on Jun 20, 2005 at 19:41 UTC
by js29a
Tiny module for high quality random number generation. Uses MZT method. The only thing you need to do is call r_univ() sub to get high-quality random number from 0.0 to 1.0.
jobs.perl.org watcher
on Jun 07, 2005 at 20:23 UTC
by diotalevi

This monitors jobs.perl.org (and eventually other sites) for postings of interest. There is separate code for watching the Minnesota Job Bank but since that's very specific, I left it out.

crontab entry to run once an hour, at 32 minutes past.

32 * * * * /home/.../bin/JobWatcher
Order your autobundle by dependency
on May 09, 2005 at 18:05 UTC
by cbrandtbuffalo
You can generate an autobundle from CPAN.pm easy enough, but it's in alphabetical order. This script uses some other modules to try to re-order the autobundle such that modules will be installed in the correct order so CPAN doesn't prompt you.

This is an initial step in my attempt to prepare for our perl upgrade and make it as easy as possible.

I'd really welcome some feedback if you try it out.

Update:Module::Dependency was a little cranky when I tried to install it (a few failing tests), so I forced it and it appears to work. I'll have to send something to the author.

Update:Turns out the topological sort in Graph sorts top-to-bottom, not bottom-to-top, so the list generated before was actually backwards. A simple reverse fixes the ordering.

weekly timesheet generator
on Mar 23, 2005 at 19:42 UTC
by multijoy
I'm not overly certain how useful this will be to others, but I couldn't find anything that did the same thing.
Basic concept is that it allows the user to time-stamp a weekly hours record, automagically creating each week's record.
Not much in the way of error checking, and I'm positive that the user interface could be less clunky. On the plus side, there 'aint that much to it.
The next trick will be to get it to email the timesheets as well!

Annotate XS code with notes on the perl API
on Nov 28, 2004 at 21:07 UTC
by diotalevi

Adds comments to your XS files with notes on the usage of the perl functions you've used. I wrote this to make noting which functions used implicit thread context or not, really easy. That and to not where a private API had been used inadvertantly.

This uses perl 5.8.6's embed.fnc file as a reference to perl's internal/public API. Perl's macros aren't listed there and so won't be covered by this utility.

mksc.pl
on Nov 10, 2004 at 20:20 UTC
by X-3mE
Extract a C shellcode from any binary program -- you must specify the function and the start/stop addresses
check syntax of perl code and pod in emacs
on Oct 11, 2004 at 14:13 UTC
by InfiniteLoop

If you use emacs, this function will check the syntax of your perl code and also run podchecker against it and display the result in a new buffer. You can call this function via the after-save-hook, and have the syntax checker run automatically. The function checks for CPerl mode.

Updated the code and the 'perlsyn' folder is shown only when there is a syntax error.(thanks to water)

Updated code to do a perl -wc (thanks to htoug)

norobotlog
on Sep 06, 2004 at 01:42 UTC
by quartertone
I always look at my Apache server log files from the command line. It always bothered me to see "GET /robots.txt" contaminating the logs. It was frustrating trying to visually determine which were crawlers and which were actual users. So I wrote this little utility, which filters out requests were made from IP addresses which grab "robots.txt". I suspect there are GUI log parsers that might provide the same functionality, but 1) i don't need something that heavy, 2) I like to code, 3) imageekwhaddyawant.
Dynamically Generating Mac OSX Terminal.app Colors
on Aug 28, 2004 at 17:15 UTC
by techy
I recently got a new iBook to play around with. My only disappointment was that the default Terminal.app uses the standard boring black text on white background. Inspired by the perlmonks node "to generate a set of well contrasted colors" as well as this article on macosxhints, I wrote a script to dynamically change the colors of Terminal.app on each login.

mask.pl_v0.1_alpha
on Jul 18, 2004 at 20:22 UTC
by X-3mE
This small script generates obfu's: you need a mask file (full of #'s), and your source perl file (without hash-bang). Simply call mask.pl source.pl mask.image and redirect the stdout somewhere, and here's your obfu.
Perl cheat sheet On-the-go
on Jun 26, 2004 at 11:59 UTC
by Aragorn
Juerd Waalboer's Perl 5 Cheat Sheet as an iPod Note.
DateTime::Calendar::Discordian
on Jun 09, 2004 at 23:43 UTC
by jaldhar
A module that implements the Discordian calendar like the ddate(1) program on Linux. Implements the DateTime API for compatability with other calendar modules.
Basic CPAN tester stats
on Jun 03, 2004 at 12:34 UTC
by LTjake

I was interested in some basic stats on how my CPAN testing client was doing. This little script will check the latest X posts (defaults to 50) to the perl.cpan.testers newsgroups for a particular author and display how many PASS/FAIL/UNKNOWN reports they have submitted.

a "screenshot":

C:\>perl tester-stats.pl cpansmoke@alternation.net Processing latest 50 items out of 142716 142716...Found 2 reports PASS: 002
Hash::AsObj
on Apr 06, 2004 at 17:51 UTC
by runrig
An experiment in AUTOLOAD and lvalue subs which resulted in a sort of combination of Hash::AsObject and Tie::SecureHash (update: actually more simply like Tie::Hash::FixedKeys or Hash::Util::lockkeys). The hash is 'secure' as long as you only access it as an object using methods, but you are free to add keys when directly accessing it as a hash ref. In the interest of keeping it simple, I'm not going to worry about handling keys like 'isa', 'can', 'AUTOLOAD', 'DESTROY', or '*::*'. And this definitely breaks can().

Updated/fixed code so that lvalue methods work better.(see reply node)

Kings Dream
on Mar 01, 2004 at 18:18 UTC
by snowsmann
This is an implementation of the "King's Dream" found in the book Chaos in Wonderland by Clifford A. Pickover. It is a complex algorithm to realize some aspects of chaos theory. It creates some very beautiful pictures and this program has three of the infinite possibilites of cool images produced. My program also allows the user to select the resolution and how many iterations to repeat the set of equations while drawing. Any comments or suggestions would be welcome. Anyone think of a good way to use colors to make this look even cooler?
Update: btw, for all who either cant get image::magick to install or are too lazy to do it, here are some images produced by this program the default image produced big(7.45 meg) image, 10000x10000 with 1.5 million iterations a not so good attempt at color scemes(in case you were wondering, i am in fact somewhat color blind) i would like any suggestion on a better way to color-enable this program
Additional ctags' Perl support
on Feb 03, 2004 at 05:13 UTC
by dmitri
This patch adds several nice features to ctags' support of Perl. More are likely to come. Summary: New feature support in perl parser:
  - support for 'use constant ABC => "xyz";' construct (ABC
    tag is created);
  - support for label constructs:
      EXIT:
    will produce a tag for EXIT;
  - support for full (package name + name) tags for
    constants and subroutines:
      package ABC::XYZ;
      sub hello {         # will create tags
                          # 'ABC::XYZ::hello'
                          # and 'hello', in case hello is
                          # called in the first way.
      }

Update: Now patch is provided instead of a link to it.

Update 2: This node 444294 provides a newer patch against ctags 5.5.4.

matrix determinants
on Nov 17, 2003 at 03:30 UTC
by ysth
A friend was reviewing precalculus (in preparation to return to school after a decade off and place into a real math class), and was working through some maxtrix determinant problems. I wrote this to help her catch arithmetic errors when calculating minors of a larger matrix. I only spent about 15 minutes, so its kind of rough, but I'm pretty satisfied, especially with how the input code handles errors.
Regexp::Approx - Use fuzzy regular expressions
on Nov 12, 2003 at 06:09 UTC
by diotalevi

This module allows you to use any of String::Approx's functions from within a regular expression. It also provides a convenience function `fuzzy_qr` which provides a regex fragment that works like an inline `scalar amatch( $pattern, $test )` expression.

use Regexp::Approx 'fuzzy_qr'; use re 'eval'; $r = qr/((?:@{[fuzzy_qr('APT')]}\s)?\w+\d)$/; $apt = ( "5678 DELAWARE AVENUE AOT 123" =~ $r )[0]; print "\$apt=$apt\n";
Notes::OLE - Lotus Domino via Win32::OLE
on Oct 31, 2003 at 21:50 UTC
by diotalevi
This module makes writing perl for Lotus Domino easy by precreating your session object and providing some utility functions for enumerating available servers and traversing document collections.
start
on Oct 14, 2003 at 07:52 UTC
by #include
I've always liked the Windows "start" commandline utility. It opens any file passed to it with the appropriate program. For example, issuing "start mysong.mp3" will open "mysong.mp3" with the default MP3 player, etc. "start" is my attempt to write a similar utility for *NIX systems. "start" uses the GNU utility "file" to determine a file's MIME type, and looks in a local flatfile database for a "command association" (in other words, the program that that MIME type is assigned to). If there isn't an entry present, it asks the user for a program to associate with that MIME type. "start" can be run in commandline mode, or (if you start it with the "-g" flag and no other arguments) it can be used with a Tk GUI. POD documentation has been included. Heavily commented.

REQUIREMENTS: GNU utility file, Perl, Tk

Devel::SummarizedWarnings
on Oct 09, 2003 at 23:37 UTC
by diotalevi

This traps warnings and prints them summarized instead of in masses. Instead of getting 3542 messages stating "Use of uninitialized value ..." at various lines you get only a few and they list all the lines it happened at and how many times.

Updated: The warnings are now displayed in the order they were first seen (they used to be in ascibetical order) and the warning messages are slightly more succinct. Instead of "on line 5 (11 times), line 8" now "on line 5 (x11) and 8".

XML::Maker
on Oct 05, 2003 at 21:58 UTC
by vadim_t
This is some code I wrote a while ago for generating XML. I hadn't heard of XML::Writer yet. Now that I tried XML::Writer I saw that it's missing a few features I want, and due to how it's written it'd be hard to add them. So I undusted this module, updated it, and added POD documentation.
Convert Gregorian/Islamic Date
on Aug 21, 2003 at 15:04 UTC
by projekt21
My wife needed to know some islamic festival dates, so I wrote a conversion module (stealing code from KDE). It still misses features like getting the day of week and others. If anybody is interested I will expand it and/or implement it into Date::Convert as a subclass. Please give me some comments.
Plaintext monthly journal generator
on Jul 20, 2003 at 00:31 UTC
by Dragonfly
I've used this script under both Win32 and OpenBSD to generate a plain-text file that I use for keeping a little journal of my thoughts.

I wrote it a long time ago (it's written in baby Perl) but have been using it monthly to make my journals, which are then really easy to edit and archive. I like keeping them in plain text format because then the entries are easy to cut and paste into other applications (emails, HTML forms, word processors, etc) without having to start a gigantic program or be online, etc.

I also like it because it simply writes a date for each day of the current month, like "Monday, July 14, 2003", with a few line breaks thrown in. That way, I can write down what I worked on that day, keep little notes or code snippets, lyrics, and so forth, and easily go back and review my month. And cross-platform date handling is a little trickier than I had initially expected, so I learned some things writing it, too.

Anyway, I know it isn't fancy, but since I use it every month, I figure somebody else out there might.

Simple "showkey" in Perl
on Jul 05, 2003 at 21:02 UTC
by Mr_Person

While working on a project, I was trying to find a way to get the status of numlock and preferably be able to tell when it was pressed. belg4mit pointed out that it was possible to get the scan code for Numlock using the showkey program. I took a look at the showkey source and found out that it does several things to the keyboard mode that allows it to capture raw scan codes. The first part is pretty much the same as saying ReadMode 4; with Term::ReadKey, but the last part I hadn't seen before and it set the keyboard to "MEDIUMRAW" mode. On closer inspection, it used an ioctl call to the current filehandle with some constants from the kd.h header file in the Linux kernel sources. It then does a bitwise AND with each character and 0x7f to get the scancode and also tests if a bitwise AND with 0x80 is true in which case the key was released, false it was pressed.

This program just uses the hard coded values taken from the kd.h file instead of including it like showkey does. There's probably a better way to do this, but I didn't know of one that would work easily. It also doesn't include as much error checking as showkey to make sure your keyboard gets back to how it should be or as many options for output.

Tablature Generator
on Jun 26, 2003 at 19:27 UTC
by crashnburn
This is a script that generates guitar tablatures from a file. It spares you the work of drawing the tablature by hand.
Lotus Notes address book export browser
on Jun 10, 2003 at 05:55 UTC
by greenFox
As I spend most of my time in cygwin with an xterm to some unix host or another swapping back to Notes for a phone number seemed like a pain :) I added the number matching facility to help auditing my phone bill.
Module 'Date'
on Jun 04, 2003 at 06:35 UTC
by nite_man
Update: This module is an OO Perl interface for management of dates and provides wide enough functionality for this. I developed this module with my colleague and it is very useful for us. I hope that this module will be useful for someone at list.
Ed2K Link Maker
on Jun 03, 2003 at 03:56 UTC
by #include
A small script that makes Ed2K links for use with the eDonkey P2P network. Just pass the script a filename as an argument, and the Ed2K link is printed to STDOUT. Uses Digest::MD5.

MASSIVE UPDATE: I pretty much rewrote the script from scratch and added a bunch of stuff: the ability to be used as both a commandline tool AND a GUI tool, the ability to hash multiple files, and some minor bugfixes. If you want to use the GUI, you must have Tk installed.
Seen.pm
on May 07, 2003 at 17:19 UTC
by defyance
A module to use with perl IRC bots to provide drop in "Seen" functionality. Basically it allows the bot to tell you the last seen action from a particular IRC user. At this point, you have to tell it which events to log, I consider this a feature. MySQL logging functionality is being considered. For now it uses a simple log file and a hash to do the logging. Some may find it pointless, some may find it interesting. I'm mainly looking for input on how to improve my code.
Simple Greeter
on Apr 30, 2003 at 15:14 UTC
by harley_frog
This is my very first "original" Perl script, inspired by "Hello World" only more intelligent. I've just started reading the Llama book and applied some of my new found knowledge to this script. Working towards a future version that will automatically input the current user's name, thus eliminating the prompt. Also working on a 12-hour clock version.

Check for updated code below.

B::Deobfuscate - Deobfuscates symbol names
on Mar 20, 2003 at 15:23 UTC
by diotalevi

B::Deobfuscate is a backend module for the Perl compiler that generates perl source code, based on the internal compiled structure that perl itself creates after parsing a program. It adds symbol renaming functions to the B::Deparse module. An obfuscated program is already parsed and interpreted correctly by the B::Deparse program. Unfortunately, if the obfuscation involved variable renaming then the resulting program also has obfuscated symbols.

This module takes the last step and fixes names like $z5223ed336 to be a word from a dictionary. While the name still isn't meaningful it is at least easier to distinguish and read.

LDAP Server TLS tester
on Jan 17, 2003 at 19:05 UTC
by beernuts
This is a chunk of code (test_tls.pl) that can be used to test LDAP servers for their ability to do TLS. It's culled from a bigger script I use to test an in-house LDAP proxy for proper installation of the script (it's in perl too) as well as the required modules.

usage:

'test_tls.pl -q' for details

Math::SnapTo
on Dec 25, 2002 at 15:14 UTC
by tachyon

The Math::SnapTo module provides several methods to snap numeric values to desired values according to various criteria.

Update

Further research has revealed that this functionality is already available in Math::Round with the nearest() function and Math::SigFigs so this module has been slated for deletion :-(

The Definitive Unit Conversion Script
on Dec 13, 2002 at 15:28 UTC
by Aristotle

Just what you'd expect from the title. :-)

New conversions are very easy to add; add a new row to the table, containing the source and destination unit and the factor to multiply by to get one from the other. If it's not a simple factor, add an array with two subrefs, one to convert from source to destination unit and another to convert backwards.

It will automatically keep applying conversions and reverse conversions to all the results it generates until it has calculated all related units from any given one.

Run it and it will tell you how to use it.

RegexLab (a wxPerl version)
on Dec 01, 2002 at 14:15 UTC
by PodMaster
Run it as a standalone app, or embed it easily into any wxPerl application, so you can test and devise regular expressions without starting a separate shell.

Install YAPE::Regex::Explain to gain insight into what you wrote. Perfect for newbies and experienced users.

http://crazyinsomniac.perlmonk.org/perl/RegexLab/

PseudoDBM
on Nov 25, 2002 at 14:07 UTC
by fruiture

PseudoDBM - pure Perl Hash-tie()ing to fixed-length-record-text-files

Well, that's all. I think it may be usefull sometimes to have a Pseudo-DBM you can use everywhere and that's readable(for control).

EDI Store and Forward System
on Oct 02, 2002 at 03:37 UTC
by diskcrash
This code is the main part of an X12 EDI (Electronic Data Interchange) store and forward system. It parses aggregate files of EDI transactions for ISA header information and forwards the EDI transaction on to an output directory. From there you can move the data to an EDI forwarder by FTP or other tools. It won't win ANY golf contests but was written to be maintainable.
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
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-03-28 21:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found