Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

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
One-line CSV Parser
on Apr 03, 2008 at 15:47
4 replies by BiffBaker
How is this for quick parsing of standard CSV?
regexp s/mode quicktest
on Mar 19, 2008 at 21:55
1 reply by halfcountplus
This is just like ReadLine regexp quicktest except it tests a string for substitutions. You can screw it up just as in your own perl code! Again, if you have an instance where this doesn't hold true comment. To be clear:

  • string: give a string to be substituted from
  • replace: give a regexp pattern to replace
  • with: give a string to replace regexp pattern
  • suffix: something to follow the last "/", eg. smx

    And all the while you can shuffle up and down using the ReadLine command history...
  • regexp for directory
    on Mar 17, 2008 at 10:05
    1 reply by halfcountplus
    this is really not much more (and less) use than plain ol' grep, but i want to use it as the basis for a GUI code scanner/viewer. It is set to check only .pl files, and requires a regexp on the command-line to work. The output (linux) is exactly what my_nihilist describes below.

    I believe McDarren, FunkyMonk, and even sort of ikegami helped me with their feedback to ranking number of occurances and Counting in regular expressions. One of several modifications courtesy of toolic, below, lead me to eliminate an unnecessary while loop (strange...) about line 22; i left the loop in comments for those who might also find it's unnecessity worth noting.

    However, it did work just fine to begin with, toolic not withstanding. There is no planet on which i would post code that i hadn't tested.

    Update #2: see my final note below, in which i take Fletch and toolic's advices about variable names and whitespace.
    mainframe screen - PCOMM - EHLLAPI
    on Mar 14, 2008 at 10:42
    0 replies by jeepj

    as I mentioned in Interact with mainframe screen, I am using the OLE interface of IBM Personal Communications 3270 emulator to perform automated tasks on a mainframe. However, some sessions get stuck when 3 or 4 sessions are used in parallel. So I tried to find another way...and I found it. Starting at version 4.1 or 4.3 (don't know exactly), a DLL EHLAPI.dll is provided with PCOMM to interface C or Java applications with the emulator, and I also found Win32::API.

    Once everything is put together, I managed to have some interaction between Perl script and the 3270 emulator with the following code.It is a just a simple one, but works, and shows an increase speed execution(and hopefully less buggy).

    Module::Install and Debian packages
    on Mar 12, 2008 at 17:00
    1 reply by dpavlin
    How many times did you wanted for Module::Install to just install available Debian packages and THEN use CPAN? I did several times. Here is quick diff to Module::Install::AutoInstall which does just that...
    ReadLine regexp quicktest
    on Mar 11, 2008 at 12:53
    1 reply by halfcountplus
    This is a very quick way way to check if a regexp will work the way one wants. It uses Term::Readline::Gnu so you get a command history (as in bash), simplifying repetative experiments. If anyone can find a string/regexp which doesn't work properly please comment. I imagine it will best serve beginners like myself in understanding things like, eg. that "7463" contains "\w", or that anything could contain "X*".

    a version of ReadLine regexp quicktest using substitution (s/) is regexp s/mode quicktest
    split file in N part
    on Mar 10, 2008 at 06:41
    2 replies by jeepj

    Hello, here is a little function (split_file) which split a file into a given number of part. This is quite simple code, but ease the dispatching of a list of reference to be handled by several jobs running in parallel.

    Of course, I am not a Perl expert, and any advise on doing it in a fancier or more efficient way is welcome

    The function is called with two arguments, the name of the file, and the number of files to create. The countLines subroutine is called to count the number of lines in a file.

    Of course, I am quite new to perlmonks, so If you find that this has nothing to do here, just tell me.


    Tk Virtual Keyboard
    on Feb 26, 2008 at 15:34
    1 reply by zentara
    This mimics the javascript virtual keyboards, which are commonly being used by online banks, to avoid keystroke loggers, when entering passwords. It's just the basic model. I still need to run tests on it to see if the letters and passwords can be kept more hidden. But if you ever wanted to play with something like this, but didn't want to go thru all the hassle of building the keyboard...... here is one for you.

    The big font I use, makes the script take significantly longer to start up, but is worth it for ease of letter reading.

    Pipe processes and Perl subroutines together
    on Feb 24, 2008 at 22:47
    1 reply by repellent
    UPDATE: (4/17/2009) Latest version of IPC::Exe is uploaded to CPAN.

    Most of the time, whenever I execute an external program:

    • in the foreground, I wish to process its output back in my Perl script.
    • in the background, I wish to leave it running behind-the-scenes, so I can carry on with my Perl script.

    I want to do the above:

    • without invoking the shell (my Perl script should interact directly with the external program).
    • with the flexibility of redirecting stdout and stderr however I wish, with as little work as possible.

    Update: (3/3/2008) I have completely restructured the code to allow for multiple processes or Perl subroutines to be piped together.

    &{ bg exe sub { "2>#" }, qw( ls /tmp does_not_exist ), exe "tac", exe sub { print "2nd cmd: @_\n"; print "three> $_" while <STDIN +> }, bg exe "sort", exe qw(cat -n), exe sub { print "six> $_" while <STDIN>; print "5th cmd: @_\n" +}, };
    is like
    { ls /tmp does_not_exist 2> /dev/null | tac | [perlsub] | { sort | cat + -n | [perlsub] } & } &
    Insert something like a hyperlink in a Tk Text widget
    on Feb 12, 2008 at 13:09
    1 reply by jdporter
    Given a Tk::Text widget, insert a string at the current insert location which is "active", i.e. when clicked, executes some function. Actually, the behavior of the "link" is defined by the caller in terms of Tk events. Clicking (<ButtonPress>) is merely one such possibility.
    cmp two HTML fragments
    on Feb 09, 2008 at 15:54
    2 replies by GrandFather

    I had a need to compare two fragments of HTML to see if they were equivalent.

    This snippet builds two HTML::TreeBuilder representations of the fragments, then recursively compares the contents of the fragments.

    To use the snippet call cmpHtml passing the two fragments as strings:

    print cmpHtml( '<p><font foo="bar" bar="1">bar 1</font></p>', '<p><font bar="2" foo="bar">bar 1</font></p>' );

    or if you already have two HTML::Elements that you want to compare you can:

    print cmpHtmlElt ($elt1, $elt2);
    Gtk2 Icon Button change text
    on Feb 08, 2008 at 14:31
    0 replies by zentara
    Hi, someone in the Chatterbox asked if I knew how to change the text in a gtk2 stock icon button. It wasn't as straight forward as I thought, as setting the label caused the icon to be lost. Muppet( perl/gtk2 maillist guru) showed me this neat sub to do it. If you are into Gtk2, this may come in handy.
    Sorting on 2 fields with the same priority
    on Feb 08, 2008 at 09:08
    2 replies by citromatik

    Recently I had to sort some records based on the values of 2 different fields, for example, given

    X 4143 61 Y 51 1325 Z 543 1543
    I wanted them sorted this way:
    Y 51 1325 X 4143 61 Z 543 1543

    Because 51 is lower than 61, and the latter lower than 543

    Surely this is nothing new, but I found the solution quite instructive, so I decided to share it here

    It uses Schwartzian transformation. An explanation could be found here

    Comments are welcome


    Variation on the "Higher Order Perl" Iterator Pattern
    on Feb 07, 2008 at 20:09
    1 reply by rjray

    This came up for some work being done at $JOB, which then went through a complete re-design, making this code no longer necessary. But I thought it was an interesting variation on an iterator.

    It probably isn't novel to have this style of iterator wrap multiple sources and present them as a single stream. What makes this different is that the sources are read from on a rotating basis; in this case it was n DBI statement handles which represented data that was split among n different MySQL hosts due to the sheer size of the dataset. For certain (mostly aesthetic) reasons, they wanted the processing stage to interleave the result-sets rather than process them in sequence.

    This is based on the wrapped objects being DBI statement handles, and the desired return-format being the sort of hash-ref structure returned by the fetchrow_hashref() method. You can write the next() as you see fit for your encapsulated objects.

    For more on clever Perl-ish iterators, see chapter 4 ("Iterators") of Higher-Order Perl by Mark-Jason Dominus (ISBN 9781558607019).

    Convert Relative to Absolute URLs on-the-fly
    on Feb 06, 2008 at 10:19
    2 replies by nikhil.patil
    This code snippet uses URI package to convert relative URLs contained in HTTP::Response objects (generated by LWP::UserAgent or WWW::Mechanize) to absolute URLs. Useful for CGI scripts that act as a proxy between the browser and website.
    Log In?

    What's my password?
    Create A New User
    [Corion]: Weird. HTML::Selector:: XPath is on v0.22 on but v0.20 on - I wonder what part of the pipeline I have to kick; most likely the metacpan indexer...
    [LanX]: ♪..♫ I shot pmdev, but I didn't shoot no janitor ...♩..♬

    How do I use this? | Other CB clients
    Other Users?
    Others romping around the Monastery: (15)
    As of 2017-03-23 13:50 GMT
    Find Nodes?
      Voting Booth?
      Should Pluto Get Its Planethood Back?

      Results (286 votes). Check out past polls.