Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
go ahead... be a heretic
 
PerlMonks

Cool Uses for Perl

 | Log in | Create a new user | The Monastery Gates | Super Search | 
 | Seekers of Perl Wisdom | Meditations | PerlMonks Discussion | 
 | Obfuscation | Reviews | Cool Uses For Perl | Perl News | Q&A | Tutorials | 
 | Poetry | Recent Threads | Newest Nodes | Donate | What's New | 

( #1044=superdoc: print w/ replies, xml ) Need Help??
This is the place to post your general code offerings.
CUFP's
Using Icons on Wx::Notebook
on Nov 18, 2009 at 12:09
0 direct replies by Steve_BZ

    Here a small piece of code showing how to create a Notebook with icons at the side (think MSN). In this example you need two icons called "users.png" and "schedule.png" 16 x 16 pixels in directory "C:\Documents and Settings\Steve\My Documents\Projects\wx" and set the $loc_windows_linux flag to "l" or "w"


[Offer your reply]
Passing negative numbers on the command line with Getopt::Long
on Nov 18, 2009 at 09:34
2 direct replies by toolic
    If you are a fan of Getopt::Long and you need to pass negative numbers to your script from the command line, here is a code snippet which can help.

    By default Getopt::Long reacts to command line arguments with a dash (-). Thus, if you want to pass -5 on the command line, Getopt::Long will strip off the minus sign and treat that as the option '5'. That will result in an error if you are checking the results of GetOptions.

    You can change the default behavior by setting the prefix to something other than '-'. For example, in the code snippet below, prefix is set to the plus sign (+). Refer to Configuring Getopt::Long. Naturally, you should make sure this is well-documented in your usage POD.

    use strict; use warnings; use Getopt::Long; Getopt::Long::Configure('prefix=+'); my %opt; GetOptions(\%opt, qw(help offset=i)) or die "error...\n"; $opt{offset} = 3 unless exists $opt{offset}; my $value = shift; print ' result = ', $value + $opt{offset}, "\n";

    Here is how it looks from the command line (I called the script add.pl):

    $ add.pl 5 result = 8 $ add.pl -5 result = -2 $ add.pl +offset -2 12 result = 10

    I recently had the need to do such a thing, but I could not find any examples of using this feature. Perhaps this will be of use to someone in the future. I uploaded my actual script to CPAN: convert_eng


[Offer your reply]
Block-sliding puzzle
on Nov 11, 2009 at 18:32
2 direct replies by ambrus

    This forum post gives the following puzzle. You have a square chess board of sides n with a piece in each of three corner squares. In each step you can push a piece in one of the four directions parallel to the sides and then it slides till it hits another piece or the side of the board. Get a piece to the center in the fewest steps possible.

    The perl script posted here computes the answer by brute force if invoked with n as the argument.

    And here's the output for n = 5. The steps are listed in reverse order.

    solution for N = 5: 11 4992: ..... ..... .CA.. ....B ..... 10 4095: ..... ..... .C..A ....B ..... 9 3209: ....A ..... .C... ....B ..... 8 2327: A.... ..... .C... ....B ..... 7 1479: ..... ..... AC... ....B ..... 6 792: ..... ..... A...C ....B ..... 5 380: ....C ..... A.... ....B ..... 4 150: ....C ..... A.... B.... ..... 3 50: ..... ..... A.... B.... ....C 2 16: A.... ..... ..... B.... ....C 1 3: A.... ..... ..... ....B ....C 0 0: A...B ..... ..... ..... ....C

[Offer your reply]
Word document email table populater
on Nov 05, 2009 at 05:18
1 direct reply by GrandFather

    This script runs through an Outlook Express mail folder and pulls out email information for all mail after a given date. The information is then inserted into a table in a MS Word document to build a correspondence list as part of a meeting agenda document.

    Much of the code dealing with the location of things is hard wired and will need to be changed in (I hope) obvious ways for your own application.


    True laziness is hard work

[Offer your reply]
Find the GCD regexically
on Nov 03, 2009 at 23:22
0 direct replies by JadeNB
    I was inspired by this Reddit thread to see if I could supplement the traditional regex primality test with a regex Euclidean algorithm. Here's the shortest one that occurred to me; it takes the two numbers (assumed to be positive integers) whose GCD we want to compute in $a and $b:
    (1 x $a) =~ /(?:$1)*(.*)/ and ($a, $b) = ($b, length $1) while $b
    At the end, $a is the GCD (and $b is 0). Life's even better if we're allowed to start with $a and $b strings of 1s of the desired length, and leave our answer in $a in the same form:
    ($a, $b) = ($b, $a =~ /(?:$1)*(.*)/) while $b

[Offer your reply]
Trick or Treat
on Oct 31, 2009 at 21:42
0 direct replies by Khen1950fx
    Since it's Halloween, I decided to decorate my terminal as a "haunted house". It looks pretty scary, but the cpan prompt wasn't quite there. I used this one-liner to change the "cpan>" prompt to Bela Lugosi's famous line: "_I_am_Dracula__". It only accepts letters or underscores, and it only changes the prompt temporarily for that session. Happy Halloween!

    #!/sw/bin/perl use strict; use warnings; my $prompt = '_I_am_Dracula__'; system("perl -MCPAN -e 'CPAN::shell($prompt)'");

[Offer your reply]
FaceBook's Word Chain Plus
on Oct 24, 2009 at 19:32
0 direct replies by Limbic~Region
    All,
    This is a follow up to Not Quite Longest Path Problem. I have written the following code which has resulted in becoming the all-time high scorer on FaceBook. It is designed to run on windows. The scoring routine allows me to write variations on get_next_word() to determine the optimal strategy.

    I may add a few more levels but I am losing interest. The code was written in a hurry but it shouldn't be too difficult to decipher. Feel free to knock me off the leader board.

    Update: I realized I didn't provide the code to construct 'word_list.db' Just replace 'four_dict.txt' with any word list of 4 letter words.

    Cheers - L~R


[Offer your reply]
Reverse Date Sorted Directory Names
on Oct 22, 2009 at 17:42
3 direct replies by grantm

    I had a need to create a set of directories - one per day. Normally I would use the date in ISO format: YYYY-MM-DD since it naturally sorts in date order. However for this particular application, I wanted reverse order - most recent date at the top, older and progressively less interesting dates following.

    This routine generates a directory name based on a unix timestamp value (default 'today'), that includes a sort code prefix to force reverse date ordering:

    sub day_dir { my($day, $month, $year) = (localtime(shift || time))[3,4,5]; my @sym = ('1'..'6', 'A'..'Z'); my $code = $sym[(138 - $year) & 31] . $sym[(11 - $month) & 15] . $sym[(31 - $day) & 31]; return sprintf('%s-%04u-%02u-%02u', $code, $year + 1900, $month + +1, $day); }

    Sample output:

    WFY-2010-01-01
    X11-2009-12-31
    X2Y-2009-11-01
    X3C-2009-10-23
    

    You could adapt it to put the day of the week ('Mon', 'Tue', 'Wed' ...) or indeed anything you like, after the sort code.


[Offer your reply]
Find encoding that should have been used
on Oct 21, 2009 at 15:08
0 direct replies by ikegami

    Trying to debug an encoding problem? The following will try to figure out what encoding was used and what encoding should have been used.

    use 5.008; use strict; use warnings; use Encode qw( encode decode ); use charnames qw( :full ); my $expected = "\N{LATIN CAPITAL LETTER I WITH CIRCUMFLEX}"; my $got = "\N{LATIN CAPITAL LETTER A WITH TILDE}" . "\N{LATIN CAPITAL LETTER Z WITH CARON}"; my @encs = ( 'US-ASCII', ( map "UTF-$_", qw( 7 8 16be 16le 32be 32le ) ), ( map "UCS-$_", qw( 2be 2le 4be 4le ) ), ( map "iso-8859-$_", 1..11, 13..16 ), ( map "Windows-$_", 437, 737, 775, 850, 852, 855, # OEM pages 857, 858, 860, 861, 862, 863, 865, 866, 869, 874, 932, 936, 949, 950, # ANSI pages 1250..1258, ), ); for my $enc_for_enc (@encs) { my $encoded = encode($enc_for_enc, $expected); for my $enc_for_dec (@encs) { my $decoded = decode($enc_for_dec, $encoded); next if $decoded ne $got; print("$enc_for_enc as $enc_for_dec:\n"); for ($decoded =~ /./sg) { my $code = ord; my $name = charnames::viacode($code); printf("(U+%04X) %s\n", $code, $name); } print("\n"); } }
    UTF-8 as Windows-1252: (U+00C3) LATIN CAPITAL LETTER A WITH TILDE (U+017D) LATIN CAPITAL LETTER Z WITH CARON

    Known bugs and limitations:

    • Doesn't provide a means to specify input without modifying the program.
    • Doesn't handle different codepoints that produce similar graphemes.
    • Should display nearest matches if there aren't any exact matches.

[Offer your reply]
Perl, please do my math homework
on Oct 18, 2009 at 01:17
1 direct reply by whakka
    In the course of my math class in the engineering program I'm currently in it's often convenient to write up little programs that perform some calculation based on a function or algorithm. However, oftentimes a reasonable program makes calculations in a different way than humans might, and it becomes a challenge to parse the print statements I insert into the code to "show my work."

    Well I finally decided to get around this problem after reading about inlining eval's in regular expressions while reading the Camel in a compromising position recently and faced with a particularly laborious exercise in my latest assignment:

    Find the number of partitions of 7 and 8 using the formula for the number of partitions of a number (all possible combinations of adding smaller positive integers):

    P(m,n) = { 1 if m or n = 1, P(m,m) if m < n, 1 + P(m,m-1) if m = n > 1, P(m,n-1) + P(m-n,n) if m > n > 1 }
    My first attempt was straightforward:
    sub partition { my ( $m, $n ) = @_; die "bad inputs" if $m <= 0 or $n <= 0; print "P($m,$n) = "; if ( $m == 1 or $n == 1 ) { say 1; return 1; } if ( $m < $n ) { say "P($m,$m)"; return partition( $m, $m ); } if ( $m == $n ) { say "1 + P($m,", $m - 1, ")"; return 1 + partition( $m, $m - 1 ); } if ( $m > $n ) { say "P($m,", $n - 1, ") + P(", $m - $n, ",$n)"; return partition( $m, $n - 1 ) + partition( $m - $n, $n ); } die "impossible!"; } MAIN: { my ( $m, $n ) = @ARGV; $n ||= $m; say partition( $m, $n ); }

    The output to this program though is actually harder to put together than doing the problem manually! The recursion is depth-first and so the program goes straight to the bottom of each branch, and yet it's more natural to evaluate one level at a time and combine. Fortunately, Perl rocks my world:

    sub P { # Returns strings! my ( $m, $n ) = @_; if ( $m == 1 or $n == 1 ) { return 1; } if ( $m < $n ) { return "P($m,$m)"; } if ( $m == $n ) { return sprintf( "1 + P(%i,%i)", $m, $m - 1 ); } if ( $m > $n ) { return sprintf( "P(%i,%i) + P(%i,%i)", $m, $n - 1, $m - $n, $n + ); } die "impossible!"; } MAIN: { local $_ = "P($m,$n)"; print; while ( /\D/ ) { # Put ints up front 1 while s/^(.+\)) \+ (\d+)/$2 + $1/; # Add the ints 1 while s/(\d+) \+ (\d+)/$1 + $2/eg; # Evaluate *one* level at a time s/(P\(\d+,\d+\))/$1/eeg; printf( "\n = %s", $_ ); } }

    And the output looks like:

    $ partition.pl 7 P(7,7) = 1 + P(7,6) = 1 + P(7,5) + P(1,6) = 1 + P(7,4) + P(2,5) + 1 = 2 + P(7,3) + P(3,4) + P(2,2) = 2 + P(7,2) + P(4,3) + P(3,3) + 1 + P(2,1) = 3 + P(7,1) + P(5,2) + P(4,2) + P(1,3) + 1 + P(3,2) + 1 = 5 + 1 + P(5,1) + P(3,2) + P(4,1) + P(2,2) + 1 + P(3,1) + P(1,2) = 7 + 1 + P(3,1) + P(1,2) + 1 + 1 + P(2,1) + 1 + 1 = 12 + 1 + 1 + 1 = 15
    Beautiful! Copied straight to the notebook.

    Update: For those interested in efficient solutions to this and other integer partition problems, Limbic~Region has this post.


[Offer your reply]
Get warranty information from a list of hosts
on Oct 12, 2009 at 05:07
1 direct reply by mickep76

    Will take a list of hosts from either STDIN or a file. It will resolve the hosts and then try to access them using SSH to extract manufacturer, serial number and product name using dmidecode. It will then access the manufacturers support page to determine the warranty of the host. Currently it works with IBM, HP and DELL.

    Assumes you are using SSH Public Keys, if your key has a password use ssh-agent to automate the password typing.

    Using it on HP has some shortcomings because of their support page. It requires you to specify country and product number, neither is possbile to extract from a host in any automated faschion. To work around this issue there is a convertion table for HP product name to product number and country will need to be specified either per subnet or one default location.


[Offer your reply]
Shell Command plugin for Padre
on Oct 09, 2009 at 18:21
0 direct replies by gsiems

    This Padre plugin allows users to type shell commands/scripts into the active document and run them. The output from the command is then inserted into the document after the command. See the POD for examples.

    Caveat emptor: I've only tested this on Linux, but it *should* work on pretty much any *nix like system.

    Update: After working more on this module and polishing things up a bit I've uploaded the new-and-improved Padre::Plugin::ShellCommand to CPAN.

    --gsiems


[Offer your reply]
Text/Code expansion plugin for Padre
on Oct 08, 2009 at 07:40
0 direct replies by gsiems

    In responding to RFC: Padre::Plugin::MyTemplates, LanX pointed me to yasnippet (which loooks seriously cool). This got me wondering just how hard it would be to create a rudementary text/code expansion plugin for Padre.

    A couple of hours later (I'm slow) and Ta-da.

    --gsiems


[Offer your reply]
Phone file transfer utility
on Oct 02, 2009 at 20:43
0 direct replies by Anonymous Monk

    I don't quite have this working the way I want it to yet, but it's close enough that I'm using it and probably won't work on it for a while. It has some room for improvement. For instance, my phone won't feed a file list to the computer through OBEX for some reason so I didn't include any way to browse the phone files. You just have to know the filename of any files you want to pull from the phone. It uses the obexftp utility because I didn't particularly feel like coding the actual file transfer from scratch, particularly since I'd have had to find and learn to use an obex library to do it.

    #!/usr/bin/perl # #This script is intended to use obex to transfer files to and from my #cell phone, a Samsung MyShot (yes, I know it has a more accurate mode +l #number, but I'm writing this thing after having given up on sleep for + the night) use strict; use warnings; use Tk; use vars qw($file $mw $phoneAddr); #Set the bluetooth address of the phone $phoneAddr="Phone BT Address"; $mw=new MainWindow(-title=>"FoneFiles"); $file=$mw->Entry(); my $fileButton=$mw->Button(-text=>"Get File to Push",-command=>\&getFi +le); my $getPutFrame=$mw->Frame(); my $getButton=$getPutFrame->Button(-text=>"Get",-command=>\&getGo); my $putButton=$getPutFrame->Button(-text=>"Put",-command=>\&putGo); #Main window geometry $file->pack(); $fileButton->pack(); $getPutFrame->pack(); $getButton->pack(-side=>"left"); $putButton->pack(-side=>"left"); #sub to pick file to push to phone. I didn't write one to pick a file +to get #from the phone because it would work with my phone even if I did. sub getFile { my $filename=$mw->getOpenFile(); $file->configure(-text=>$filename); } #sub to get file from phone sub getGo { my $varFile=$file->get(); $varFile=~s/\ /\\ /; my $notice=$mw->Toplevel(-title=>"Getting"); my $lab=$notice->Label(-text=>"Getting file from your phone. Pleas +e wait")->pack; $mw->update; $notice->update; #obexftp is a command line obex utility. #This line will use the obex push protocol to get a file from +the phone `obexftp -b $phoneAddr --nopath --get $varFile`; destroy $notice; } #sub to send a file to the phone sub putGo { my $varFile=$file->get(); $varFile=~s/\ /\\ /; my $notice=$mw->Toplevel(-title=>"pushing"); my $lab=$notice->Label(-text=>"Pushing file to your phone. Please +wait")->pack; $mw->update; $notice->update; #This command uses obex push to push a file to the phone `obexftp -b $phoneAddr --nopath --put $varFile`; destroy $notice; } MainLoop;

[Offer your reply]
Bash Parser
on Sep 30, 2009 at 05:15
1 direct reply by mickep76

    Creates a dependency and statistics report of a directory with BASH scripts.

    The script will generate a dependency report for each BASH script in the specified path.

    Right now it call's 'rpm' to get dependencies for RPM's, if your system doesn't have RPM just replace the line that calls it with an undef variable.

    Guess I will make a test for it in the next version.

    The current output looks like below for each script and in the end there is a summary for all scripts.

    /etc/init.d/multipathd |-- binary: basename |-- binary: test |-- teardown_slaves | |-- binary: pwd | |-- binary: sed | |-- binary: echo | |-- binary: readlink | |-- function: teardown_slaves | |-- binary: sed | `-- binary: echo |-- binary: test |-- binary: echo |-- binary: touch |-- binary: echo |-- binary: echo |-- binary: echo `-- binary: echo /etc/init.d/multipathd Code lines: 102 Comment lines: 13 Empty lines: 12 Total lines: 127 Function(s): teardown_slaves Uses function(s): teardown_slaves Uses binarie(s): basename echo info pwd readlink rm sed test touch Uses RPM(s): coreutils-5.97-19.el5 info-4.8-14.el5 sed-4.1.5-5.fc6

    The summary looks as following. This output is slightly cut down and is taken from CentOS 5.x running a report on "/etc/init.d"

    ------------------------------------------- Duplicate local function names: 5 stop 5 start 2 status 2 restart 2 condrestart 1 do_restart_sanity_check 1 makedev 1 start_isdnlog ... ------------------------------------------- Most used functions: 18 stop 12 start 6 restart 4 status 4 invoke_command ... ------------------------------------------- Most used binaries: 422 echo 72 rm 57 touch 40 grep 36 test 30 awk ... ------------------------------------------- Most used RPM's: 671 coreutils-5.97-19.el5 50 grep-2.5.1-54.2.el5 30 gawk-3.1.5-14.el5 19 util-linux-2.13-0.50.el5 10 sed-4.1.5-5.fc6 9 file-4.17-15.el5_3.1 4 xorg-x11-xfs-1.0.2-4 ... ------------------------------------------- Total code lines: 4438 Total comment lines: 989 Total empty lines: 705 Total lines: 6132 Total files: 51

    Without further ado here's the code in all it's ugliness.

    Updated to v0.9 Solved some of the issues mentioned in the replies. Thanks again for the input.


[Offer your reply]
 (1-15) of 300 Next entries--> 

Add your CUFP
Title:
CUFP


  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Login:
    Password
    remember me
    What's my password?
    Create A New User

    Community Ads
    Chatterbox
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users
    Others exploiting the Monastery: (10)
    Corion
    GrandFather
    wfsp
    atcroft
    Random_Walk
    herveus
    Eyck
    biohisham
    gnosti
    raisputin
    As of 2009-11-21 09:53 GMT
    Sections
    The Monastery Gates
    Seekers of Perl Wisdom
    Meditations
    PerlMonks Discussion
    Categorized Q&A
    Tutorials
    Obfuscated Code
    Perl Poetry
    Cool Uses for Perl
    Perl News
    Information
    PerlMonks FAQ
    Guide to the Monastery
    What's New at PerlMonks
    Voting/Experience System
    Tutorials
    Reviews
    Library
    Perl FAQs
    Other Info Sources
    Find Nodes
    Nodes You Wrote
    Super Search
    List Nodes By Users
    Newest Nodes
    Recently Active Threads
    Selected Best Nodes
    Best Nodes
    Worst Nodes
    Saints in our Book
    Leftovers
    The St. Larry Wall Shrine
    Offering Plate
    Awards
    Craft
    Snippets Section
    Code Catacombs
    Quests
    Editor Requests
    Buy PerlMonks Gear
    PerlMonks Merchandise
    Planet Perl
    Perlsphere
    Use Perl
    Perl.com
    Perl 5 Wiki
    Perl Jobs
    Perl Mongers
    Perl Directory
    Perl documentation
    CPAN
    Random Node
    Voting Booth

    Future historians will find that the material characteristic of the current era is...

    Aluminium
    Plastic
    Oil
    Water
    Carbon dioxide
    Copper
    Iron
    Silicon
    Salt
    Uranium
    Hydrogen
    Other

    Results (729 votes), past polls