Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

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
Get a structured tally of XML tags
on Apr 23, 2009 at 21:42
0 replies by graff
Get a quick snapshot of the quantity and structure of elements in an XML file -- useful for getting acquainted with some new XML source, or for confirming expectations about XML data you created. (Yes, it is worthwhile to use XML::Parser in a one-liner...)
On-disk hash/array data structures
on Apr 16, 2009 at 16:33
0 replies by repellent
Please note that there are already modules that do this: DBM::Deep and MLDBM come to mind.

Here are a couple of drop-in functions to return a hash or array reference to a temporary DB_File. Not really a new idea - just had to be put together for ease.

This serves as a useful hack if we wanted our large data structure to be on-disk instead of in-memory. Remember to untie the references when done using them.

  • Use db_ref() to generate a new hash/array reference.
  • Use db_open_ref() to open an existing DB_File.
use warnings; use strict; use Data::Dumper; my $h1 = db_ref("HASH"); my $h2 = db_ref("HASH"); $h1->{hello} = { 123 => 456, 789 => [ 3, 4, 5 ] }; $h1->{crazy} = 747; $h2->{world} = [ 5, 6, 7, $h1->{hello} ]; print "key> $_\n" for keys %{ $h1 }; print Dumper($h2->{world}); untie %{ $h1 }; untie %{ $h2 }; my $a = db_ref("ARRAY", 1); # no serialization push @{ $a }, 1..4; print "item> $_\n" for @{ $a }; untie @{ $a };
Win32 BrowseForFolder
on Apr 05, 2009 at 09:01
0 replies by nikosv
Win32 BrowseForFolder. Creates a dialog box that enables the user to select a folder. This small procedure is part of a larger programm that lets you choose a directory and manipulate its contents i.e combines nicely with File::Find
Net::Telnet::Cisco and IOS-XR
on Mar 19, 2009 at 16:01
2 replies by VinsWorldcom

Cisco IOS-XR introduces a new prompt format that is "breaking" Net::Telnet::Cisco. Basically, the Route Processor and CPU instance is added with a colon ":" before the router hostname. I was wondering why my Telnet sessions were "failing" but the logs showed they connected and got the prompt.

I looked for an update to Net::Telnet::Cisco, but the latest version I could find was 1.10, which is what I have installed. To get around this, I used the -prompt option when calling Net::Telnet::Cisco->new() from my script.

Under the "sub new" procedure in, I found the existing prompt regex (you can't miss it). I copied that code and added the new piece and passed that in when I make the Net::Telnet::Cisco->new() call via the "-prompt" option. (See Net::Telnet for more info.)

All we're doing is adding a check for the Route Processor and CPU instance and colon before the hostname - optionally, so we don't break what's currently working. This is done with the addition of:


near the beginning of the existing regex.

tree-oriented use of HTML::FillInForm
on Mar 13, 2009 at 13:26
0 replies by metaperl
I repeat my bug report:
Not all templating systems are string-oriented. HTML::Seamstress is not. It works with HTML::Element instances. As such, it would be nice if the result of filling in the form could be returned as a tree for further processing by HTML::Element methods. As it stands, I am forced to parse the results of HTML::FillInForm back into a tree (even though it was a tree before HTML::FillInForm stringified it).
Now, just consider how much is being done.
  1. seamstress has an HTML tree that it wants the form filled in on
  2. seamstress converts this to a string
  3. FillInForm parses the string into an HTML tree and then fills in the form
  4. FillInForm converts the HTML tree to a string
  5. seamstress re-parses the HTML for additional processing
If FillInForm could receive and return trees, my apps would be much faster.

For the time being, I at least need to turn this multiline process into a single function call, so here it is.

Of course,

functional programming: scan function
on Mar 12, 2009 at 15:49
1 reply by metaperl
I needed a scan function for some data processing I am doing. Unfortunately Sub::Curried does not work, so I cannot use it's scan function.

Language::Functional has a broken test suite. And I can't figure out how to fix its issues.

fp does not have a scanl function. I considered contributing this code to it, but am turned off by the semantics of the reduce function... I think that would be better named behead. It also potentially conflicts with List::Util in that respect.

So here we have the scanl function, a staple of functional programming, available in standalone fashion. As you can see, it behaves the same as scanl for haskell

One-liner: Inspecting a browser cache with File::MMagic
on Feb 27, 2009 at 21:01
0 replies by missingthepoint
Browser caches are interesting places. Firefox, in particular, has many files all with intuitive names like 'FA509DE4d01', and no extensions. Fortunately Unix culture has a method for bringing order to this chaos: 'magic' databases, or files containing bytes found in particular types of files. These allow you to guess a file's type based on its contents. Perl provides 'magic' support in the form of File::MMagic, and the following one-liner uses it to print the guessed types of all files in the current directory. (Update: typo, and removed useless Data::Dumper)
Win32: Launch and wait for Pageant before resuming
on Feb 03, 2009 at 20:06
0 replies by bart

I use PuTTY tools from a Perl script, in particular pscp (PuTTY scp), and I use Pageant for automated authentication, so that I don't have to type in my password for every single file to transfer.

But my Pageant uses a password to its vault, too. So Pageant must already be running and ready before I attempt to scp files, or I still have to type in my password, every time, manually.

And that's where this snippet comes in. It tries to start up Pageant, waits till it comes back and/or until you typed in the password and pressed return, and only then resumes.

I use Win32::Process to launch Pageant, and one of 2 things may happen:

  1. Pageant wasn't running and it will pop up a login dialog box asking for the password. And then, after the dialog box closes, the process will continue running in the background, with an icon in the systray. If you Wait for that process to finish, you can wait for a very long time...

  2. Pageant was already running in the systray and the process immediately exits.

So, what does the snippet do?

  1. It reads the parameters to launch Pageant with from a Windows shortcut file (*.lnk file) — You may skip this part.

  2. It launches Pageant using Win32::Process, and it waits for 2 seconds for it to finish. So, in case (2) it'll immediately return, but in case (1) it'll give the program enough time to show its password dialog window.

  3. It uses Win32::GuiTest to see if the password dialog is still up, and polls, and waits until it closes.

Programming in Perl without semicolon
on Jan 30, 2009 at 16:50
4 replies by buetow
I've a few good friends who like Python a lot (yes it is a nice Language, but I like Perl more). One difference is, that you can program in Python without using semicolons. Well, this is possible using the Perl language too, like the following code demonstrates it (it calculates fibonacci numbers, however without use strict). I don't tell, that you will have any benifit by not using a semicolon. But I think this is a funny way of programming in Perl. Enjoy :)
Obfuscated accessor
on Jan 27, 2009 at 15:16
0 replies by bluescreen
I was thinking if there any chance to write an accessor in just one line, and I came up with the following code. Of course I wouldn't use in a real project because its unreadable but it might worth sharing. The good thing is just replacing subroutine name creates a new accessor.
Vow Triptych
on Dec 30, 2008 at 10:22
3 replies by hashED
So I'm getting married in October, and I started thinking about wedding vows, and so I wanted to get a better feel for what other people spend most of their wedding vow-ing time talking about. Here's a little script that came out of that effort. It takes a text file full of wedding vows (which you'll have to provide for yourself) and prints the text's triptycs.
Dump JudyHS
on Dec 29, 2008 at 17:57
0 replies by diotalevi

This dumps the contents of a Judy::HS/JudyHS(3) array. I had to violate its API to do this. JudyHS is constructed as nested Judy::L/JudyL(3) arrays. The top level encodes the string length. The next level encodes a hashing. Each additional level encodes another 4 or 8 bytes of the input string until no more are needed and it terminates in a C struct which contains the key and value.

The below example loaded Judy::HS with a map from string to line number. It's completely arbitrary and I did it just to demo to myself that I could enumerate the contents of Judy::HS if I needed to.

Judy.h in the Judy C library has a nice, readable description of the structure that's being dumped here.

on Dec 02, 2008 at 10:47
2 replies by gok8000

Hi all,

Sometimes I have to change words inside text files. When this happens, and when I know what to search for, I use this program.

Commifying sensibly
on Dec 01, 2008 at 09:57
2 replies by oko1

Recently, I was thinking about that example in the docs where they demonstrate a method for inserting commas into a numerical string. Now, I realize that they're trying to illustrate a specific mechanism with regexes... but that thing is just clumsy and awful and obfuscated for any Perl beginner. So, just for my own entertainment, I decided to see how I'd do it "for real" - i.e., in the best way possible rather than by this contrived method.

Herewith, humbly, I present a couple of options. :)

[untitled node, ID 726208]
on Nov 26, 2008 at 15:06
2 replies by redleg7
Log In?

What's my password?
Create A New User
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2017-03-22 22:52 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (276 votes). Check out past polls.