Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Snippets Section

( #1967=superdoc: print w/ replies, xml ) Need Help??

This section is now closed for posting code. Please use Cool Uses For Perl instead.

New Snippets
Sybase BCP date formatter
on Nov 21, 2008 at 17:53
1 reply by runrig
When using Sybase's "bcp out" to a delimited file, fix the default date format to be something more portable (and sortable). This assumes a pipe delimited file, adding options to change that is left as an exercise. This is a function instead of a standalone script so that it can be included within another program.
ColorRamp1785-w-Tk
on Nov 19, 2008 at 14:22
0 replies by zentara
BrowserUk's nice post in ColorRamp1785 had one little shortcoming.... there was no selection method for choosing the right color. Here is a little Perl/Tk front-end to his subs.
ColorRamp1785
on Nov 19, 2008 at 01:55
1 reply by BrowserUk

A while ago I had need of a color ramp and found one on-line which I implemented in Perl and have made regular use of since.

However, that ramp only allows a maximum of 1021 distinct colors, (four edges of the 24-bit color cube with 3 shared values), and I recently had the need of more. So I extended the ramp to start at black and transition to white: black->blue->cyan->green->yellow->red->magenta->white thus transitioning 7 edges of the color cube giving me 1785 distinct colors.

Update: seems I did a piss poor job of extracting the code below from the application where I used it, and attempting to generalise it. I believe I've corrected that now.

A Tribute To The Monks Of Wisdom
on Nov 15, 2008 at 20:41
6 replies by koolgirl

May I have a drum roll please!

Ok, Monks, I have spent quite a bit of time contemplating whether or not this write-up would be a complete waste of time due to it's insignificance, and whether or not it might even warrant some serious XP loss on my part (though I prayed that it wouldn't *big pouty eyes*). However, I'm doing it anyways, so here goes....

This is a tiny snippet of code, an excersise which teaches basic file manipulation, which is my current venture into the world of Perl. It means nothing, I'm sure, to the code catacombs per se, however, it's significance lies in it's construction. I wrote this in about 45 minutes, encountered several problems, researched them, de-bugged my code, got it working, and even used, at least to a point, a less verbose approach than usual, and I did it all by myself. It is the very first time in several months of hard core studying, that I have accomplished this feat. To be blunt, I just couldn't be more proud of myself...I even did a dance, a 5 minute long dance mind you, after seeing the beautiful output.

Now, before you hit the -- vote while thinking to yourself "I can't believe this absurdity...I could've written that in my sleep and never even needed to de-bug a thing", please allow me to quickly end this monstrosity by explaining why I went ahead with it.

There are a countless number of you, who have dedicated your precious time to answering my many questions over the last few months, all of them revolving around my inability to de-bug my own code without asking another Monk to hold my hand. I wanted to show all of you who were nice enough to help, that your effort was not in vain...ya'll taught me how to de-bug my code. This is a testament to every monk that has ever answered a SoPW question, just to watch that same monk who asked, completely ignore it and continue to ask about it over and over again. I know the experts on here get frustrated with us newbies for such things. So, I wanted to give tangible proof, that the Perl Monks are fantastic teachers and should be praised for it.

So, I hereby dedicate this to every Monk on here, that has ever taken the time to answer a newbie question, in an effort to further a fellow Monk's knowledge. Monks it is truly a privilege and an honor to be a recipient of your guidance!

UPDATE: Fixed the typo and forgotten close. Thanks hossman :D

UPDATE:

Yes, I do realize that the file tests could have been performed without opening them, however, I didn't understand how to open files from the @ARGV, as it was my first time calling a program with file names behind it on the command line, so, I went ahead and researched it and incorporated it into my program, just to give myself the experience.

Zero forgetfullness
on Nov 14, 2008 at 18:58
4 replies by Odinator
Ok I have only been into Perl for a couple weeks (I am still technically on the Llama book), but when I found out that their were all these modules that let me experiment with the fabric of time and space, and artificial intelligence, I could not resist. Anyways I have forgetfullness down to 0.0000000 and I made a script I think is kind of neat. Anyways, the quantum and neural network modules go together like ham and swiss. Yes I know its just adding and removing from the tutorial program on the cpan. But I want to show everyone how great quantum and neural net modules mix. I imagine genetic algorithms would be fun to test to, but they do not go as smoothly with Quamtum mods as the NN`s do. I will be experimenting and adding to this alot tonight, and in the next few days, to see what else I can create. Any suggestions into ways I can take this farther, or ways a more experienced programmer could make this better, or even usefull. Would also be interesting. So without further adew, here we go..
Delete an Excel worksheet
on Nov 10, 2008 at 15:29
0 replies by PFudd
My input Excel file has four worksheets; I wanted to delete worksheet #2 and save the spreadsheet. There is no function to delete a worksheet in Spreadsheet::ParseExcel nor SpreadSheet::WriteExcel, as they assume that if you didn't want the sheet, you wouldn't have created it.
CPAN searchplugin for firefox 3
on Nov 08, 2008 at 10:28
1 reply by sir_lichtkind
beside smart bookmarks you have searchplugins in firefox. unfortunately in the mozilla addon repo doesn't have one for CPAN, but David showed how to get one. but because ff3 has a new API we need an update which i deliver here now:
Search for <n>th occurrence of regex
on Nov 05, 2008 at 15:02
1 reply by repellent
The following form searches for the <n>th occurence of a regex:
Beautiful .. operator
on Oct 28, 2008 at 11:31
2 replies by grizzley
Some time ago I was preparing some presentation about Perl and while reading about flip-flop I was wondering how to easily explain how it works. I couldn't. It works in such intuitive way one can tell "get me everything between /start/ and /stop/". But to explain how it does it, you need two pages of paper :) Ok, I exaggerate a little. Anyway, I discovered another useful construction with the same properties: it can be easily described as "take everything between /start/ and (/end/ which is not inside other /start/ .. /end/ block)". Or shorter: "take /start/ .. /end/ block which can include other /start/ .. /end/ blocks", but kids don't try to analyze it at home :) It can be easily extended to two or more levels of nesting. Pity, I didn't discover it before 'beautiful Perl YAPC'... :)
Randomly select N lines from a file, on the fly
on Oct 08, 2008 at 21:00
1 reply by blokhead
Many people know the trick from perlfaq about how to choose a line uniformly at random from a file (or pipe), without knowing a priori how many lines are coming.

Here is a generalization of the method that chooses a random subset (without repetition) of N random lines from a file. The method only needs to keep N lines of the file in memory. It also preserves the ordering of lines. If the little script is named sample, you use it like this:

$ sample 10 somelongfile.txt ## to get 10 random lines $ some long command | sample 50 > mysample.txt
Proof of correctness is fairly straight-forward by induction.

Note: perlfaq recommends File::Random for the case of choosing 1 random line. And indeed, the random_line function in that module has an option to choose more than 1 line. However, it selects with repetition.

push to a referenced array
on Sep 27, 2008 at 16:10
2 replies by biga
This useful function performs 'push' into a referenced array. It creates the array if it doesn't exist.
SYNOPSIS:
my $a={};
ref_push $a->{ARRAY}, "some", "list";
But the code is a bit obfuscated... %)
Generate uniform random partitions of a number
on Sep 25, 2008 at 12:00
1 reply by ambrus

The following snippet shows how to generate uniform random partitions of a number fast.

generating random thruth-tables
on Sep 24, 2008 at 09:34
1 reply by neniro
I needed a bunch of truth-tables, with random result-rows, as exercises for logical minimization. An easy task utilizing Perl:
ISO 8601 week number
on Sep 11, 2008 at 06:09
2 replies by wol
Many businesses operate along according to week numbers and ignore months completely, so perl-y business apps may need to calculate them. ("We synergise our assets in week 42, and leverage our ducks into line in week 45", etc)

It's possible to use the Date::Manip or POSIX modules, but they both have some caveats.

Seeing as I only found how to use the above after I'd rolled my own, I thought I'd share both the information and my own solution, so that (crossed fingers) Google might help anyone else needing the same...

Copying a directory and its contents while displaying a status
on Aug 04, 2008 at 18:13
2 replies by hiseldl

Uses File::Copy::Recursive, but wedges another 'copy' sub so that a progress bar, or some other hook, can be displayed or run.

update:

The real trick to this particular snippet is determining that File::Copy::Recursive uses File::Copy::copy, but the copy sub is imported into the File::Copy::Recursive namespace rather than its own namespace. If you try to hook File::Copy::copy, it will not work.

For completeness, thank you jdporter, here is what it would look like if Hook::LexWrap was used:

use Hook::LexWrap; use File::Copy::Recursive qw(dircopy); use strict; use vars qw($dir_from $dir_to); $dir_from = "/tmp/from"; $dir_to = "/tmp/to"; $|=1; # Using Hook::LexWrap my @dirs; wrap *File::Copy::Recursive::copy, pre => sub { @dirs = @_ }, post => sub { printf "copying %s to %s. \r", @dirs }; dircopy($dir_from, $dir_to); print "\n";
Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2014-08-01 10:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Who would be the most fun to work for?















    Results (2 votes), past polls