Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Cool Uses for Perl

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

This section is the place to post your general code offerings -- everything from one-liners to full-blown frameworks and apps.

Alternating Case Regex
1 direct reply — Read more / Contribute
by QM
on Dec 14, 2019 at 13:44
    Elsewhere I saw a question asking about matching alternating case strings. Here's the regex, and a test script.

    It looks a bit clunky, but it works.

    Here's the test script:

    #!/usr/bin/env perl # Test for alternating case regex use strict; use warnings; # Generate all lower/upper combos up to 5 characters with the characte +rs A-E my @test_strings = qw( a A ab aB Ab AB abc aBc Abc ABc abC aBC AbC ABC abcd aBcd Abcd ABcd abCd aBCd AbCd ABCd abcD aBcD AbcD ABcD abCD aBCD AbCD ABCD abcde aBcde Abcde ABcde abCde aBCde AbCde ABCde abcDe aBcDe AbcDe ABcDe abCDe aBCDe AbCDe ABCDe abcdE aBcdE AbcdE ABcdE abCdE aBCdE AbCdE ABCdE abcDE aBcDE AbcDE ABcDE abCDE aBCDE AbCDE ABCDE ); # test all strings, save them in a hash for sorting later my %results; for my $test (@test_strings) { my $result = $test =~ m/^([a-z]([A-Z][a-z])*[A-Z]?|[A-Z]([a-z][A-Z +])*[a-z]?)$/; $results{$test} = $result; } # print the results, sorted by result for my $key (sort by_result_or_length_or_alpha keys %results) { printf "%10s %d\n", $key, $results{$key}; } exit; sub by_result_or_length_or_alpha { ($results{$b} <=> $results{$a}) or (length($a) <=> length($b)) or ($b cmp $a) }

    Here's the output:

    a 1 A 1 aB 1 Ab 1 aBc 1 AbC 1 aBcD 1 AbCd 1 aBcDe 1 AbCdE 1 ab 0 AB 0 abc 0 abC 0 aBC 0 Abc 0 ABc 0 ABC 0 abcd 0 abcD 0 abCd 0 abCD 0 aBcd 0 aBCd 0 aBCD 0 Abcd 0 AbcD 0 AbCD 0 ABcd 0 ABcD 0 ABCd 0 ABCD 0 abcde 0 abcdE 0 abcDe 0 abcDE 0 abCde 0 abCdE 0 abCDe 0 abCDE 0 aBcde 0 aBcdE 0 aBcDE 0 aBCde 0 aBCdE 0 aBCDe 0 aBCDE 0 Abcde 0 AbcdE 0 AbcDe 0 AbcDE 0 AbCde 0 AbCDe 0 AbCDE 0 ABcde 0 ABcdE 0 ABcDe 0 ABcDE 0 ABCde 0 ABCdE 0 ABCDe 0 ABCDE 0

    Quantum Mechanics: The dreams stuff is made of

TK font control Linux Windows
1 direct reply — Read more / Contribute
by boleary
on Oct 03, 2019 at 09:24

    I've been struggling for a couple of years with the differences between the Linux and Windows versions of my TK based perl tools.
    So one of my TK UIs in windows would fit nicely on a 1920x1080 screen,
    but would expand strangely and overflow the display when opened in Linux.
    It would take me several hours to re-layout the GUI to work with both applications
    It turns out that the main problem was default font sizes.

    The default Linux font was Helvetica 12 for most widgets, and the Windows font is Arial 8.
    Once I figured that out, I looked around for some solutions to controlling the font sizes.
    The Mastering TK books talk about using Xdefaults or TK::CmdLine,
    but I am distributing my tools as wrapped executables and I cannot count on any kind of pre-existing environment

    I finally found this link from the TCL wiki

    It was close to what I wanted (in TCL-TK ) But I wanted to have a little more control and set all the Label type widgets to use bold text
    and all the entry type widgets with the same font but not bold

    I came up with this solution that I wanted to share (and be able to search for later) I wrote a sub to defined the default fonts for my application
    and then I call that sub immediately after creating my MainWindow

    #main application our $MAIN_WINDOW=MainWindow->new; #make call here to init the fonts from the very beginning &init_mw_fonts($ctlRef,$MAIN_WINDOW); $MAIN_WINDOW->title("CadEnhance:Part Builder Schematic Symbol Creator" +); $MAIN_WINDOW->configure(-menu=>my $menubar=$MAIN_WINDOW->Menu); # # # MainLoop; sub init_mw_fonts{ #set the default font types or all of our widget classes my $ctlRef=shift; my $mw=shift; require allToolCtlVariables; my $boldFont =&my_tk_cfg_vars("BOLD_FONT") || &all_tk_cfg_vars("BOLD +_FONT"); my $normalFont =&my_tk_cfg_vars("NORMAL_FONT") || &all_tk_cfg_vars(" +NORMAL_FONT"); my $textFont =&my_tk_cfg_vars("TEXT_FONT") || &all_tk_cfg_vars("TEXT +_FONT"); #first set ALL fonts to $normalFont $mw->optionAdd("*font",$normalFont); #then we pick and choose the items we want to be bold foreach my $boldClass (qw(Checkbutton Label Listbox Button Menu Menubutton Message Radiobutton Scale + ProgressBar)) { $mw->optionAdd("*$boldClass.font",$boldFont); } #now set the text Font $mw->optionAdd("*Text.font",$textFont); } #This subroutine lets us program the fonts we want to use #and we can create a similar one for each application called #my_tk_cfg_vars which will override the global one sub all_tk_cfg_vars { my $selection=shift; my %gui_vars=( ENTRY_WIDTH=>80, CFG_ENTRY_WIDTH=>40, DT_ENTRY_WIDTH=>98, TEXT_WIDTH=>110, BACK_GROUND_COLOR=>"light grey", YPAD_SMALL=>0.5, YPAD_MED=>1.0, YPAD_LARGE=>5.0, XPAD_SMALL=>0.5, XPAD_MED=>1.25, XPAD_LARGE=>15, LABEL_FONT=>"Arial 9 bold", BOLD_FONT=>"Arial 9 bold", NORMAL_FONT=>"Arial 9", TEXT_FONT=>"Helvetica 10", ); if (defined ($gui_vars{$selection})) { return $gui_vars{$selection}; } else { return 0; } } sub my_tk_cfg_vars{ my $param=shift; return ""; #or override the values defined in all_tk_cfg_vars }

    Hopefully this may help someone else who might be hitting the same issue

Perl Tk run on Android. It works
1 direct reply — Read more / Contribute
by zentara
on Sep 17, 2019 at 13:46
    Hi,this is a step by step guide, but your experience might differ.

    I am using Android 7.0 Nitrogen on a Nexus 7.

    (1) Go to google play store and install the termux app. Now follow the instructions for setting up a graphical environment at termux gui. I suggest using the tigervnc as the XSDL dosn't work on Android later than v4. Also install the VNC Viewer app. The instructions explain how to setup fluxbox and openbox but I had trouble getting them to load. The default TWM works fine. Basically the commands until now should be "pkg install x11-repo" followed by "pkg install tigervnc aterm"

    (2) Install the cc with "pkg install clang libxorgproto" I found that X11/X.h file was in libxorgproto and is needed.

    (3) While in termux, and at the prompt "pkg install mc" to naviagte and edit :-). Create and edit the file ~/.bashrc and add export DISPLAY=":1"

    (4) Edit the ~/.vnc/xstartup file to say this:
    aterm -geometry 80x24+10+150 -ls &
    twm &

    At the termux prompt, type "vncserver -localhost" and you should get a message saying :1 was started. If not do a "killall Xvnc" and try again. Once you are running, start the VNC Viewer app and enter for address. 5900 + display number

    You should see a black screen in your VNC Viewer with an aterm. In the aterm type "pkg install perl" then "pkg install Tk".

    The Japanese fonts don't seem to work, and the test takes long, but the Tk windows are opening.

    You may find that cpan's install fails at make test, so then just navigate to ~/.cpan/build/Tk-****/ and type "make install". Then you will find that the shebang line #!/usr/bin/perl needs to be symlinked or changed to /data/data/com.termux/files/usr/bin/perl. YMMV. As an easy solution, just start all Tk programs like "perl mytkapp"

    Good luck, have fun. Perl Tk is way easier than Android programming. :-)

    I'm not really a human, but I play one on earth. ..... an animated JAPH
Graphics::Framebuffer + MCE::Hobo and threads
No replies — Read more | Post response
by marioroy
on Sep 09, 2019 at 02:25


    I'm posting to share something wonderful. MCE and MCE::Shared have reached 1.850. They now work reliably with Graphics::Framebuffer. Three new examples were added to the framebuffer folder on GitHub. Curently, Graphics::Framebuffer works on Linux maybe FreeBSD. The 3 examples,, and use MCE::Hobo, threads (yes this too), and MCE::Child respectively.

    I also updated the PDL demonstration on GitHub, recently. That works on Windows similarly to runing on UNIX.

    Me ka aloha pumehana (kind regards), Mario

simple game of life by new hand
4 direct replies — Read more / Contribute
by glycine
on Sep 08, 2019 at 05:42

    hello! when I first read some things about game of life, it let me amazing. some days ago, suddenly, I find maybe I can make one by my self with perl! although there are a lot of game of life on the internet, wrote by Rust, c++, java... but I think it will be a interesting practice, so I write this :) ( Conway's Game of Life on the Wiki: Conway's Game of Life )

    this code can't be expand to other rules of cell automata, and have a lot of pointless subroutine.

    here is code:

    new: after roboticus give me advice, I change the name of variables and subroutines, delete a bug, so, here is new version.

    I know that using OOP is better, but I am still learning about this, um... I will try it...

    thanks you for read this! p.s., I try to use readmore, but I don't know it if work in preview...

Lexing C++
3 direct replies — Read more / Contribute
by Random_Walk
on Aug 31, 2019 at 19:17

    So folks,

    today I need to makes some sense of C++ files. I will need to parse out function signatures, and I have tried this with regex before, it gets messy especially around templates. Now a similar requirement has reared it's head so step one, lex the code. without further ado here is my attempt at lexing C++. The Lexer is called with an open file handle to a C++ source file. This is lexed into an array of tokens, that is then handed on to the parser.

    What do you think, is this going to give me a nice labeled stream and make parsing a dream, or am I stumbling into know gotchas? Does it qualify as cool?


    Pereant, qui ante nos nostra dixerunt!


    More compiler directives added (I know Kung Fu)
1 direct reply — Read more / Contribute
by Anonymous Monk
on Aug 30, 2019 at 05:25
    Saved as
    #!/usr/bin/perl my $h = "hello"; my $w = "world"; for (my $i = 0; $i < 3; $i++) { print "$h $w \n"; } my $n = 0; my $x = 100000000; for (my $i = 0; $i < $x; $i++) { $n++; } print "\n"; print "Counted to $n \n";
    perl < | tee hw.cpp && g++ hw.cpp -o hw.o && time pe +rl && time hw.o
    #include <iostream> int main(){ //!/usr/bin/perl std::string h("hello"); std::string w("world"); for (double i=0; i < 3; i++) { std::cout << "" << h << " " << w << " \n"; } double n=0; double x=100000000; for (double i=0; i < x; i++) { n++; } std::cout << "\n"; std::cout << "Counted to " << n << " \n"; return 0; }
    Observed discrepancy:
    perl	0m3.213s
    c++	0m0.298s
    Cool use for Perl, to learn a little C++!
Moving, copying and renaming files with new tool
2 direct replies — Read more / Contribute
by siberia-man
on Aug 14, 2019 at 05:22
    Hello Monks,

    I re-invented the wheel and decided to share it. This is script that is supposed to be used as a tool for moving, copying and renaming files. In the beginning I called it as "the re-invented wheel" becuase there are a few implementations for such kind of functionality. I found 3 of them at least (all are mentioned in the documentation). While developing the script I borrowed some good ideas from those implementations and adapted for my script. And I applied my vision of the conveniency.

    Here I show some scenarios from real life I've really met:

    Removing prefixes and suffixes:

    file-rename 's/^[^.]+\.//; s/\.[^.]+$//' ...
    Enumerate files:
    file-rename 's/^/sprintf "%02d. ", $NR/' ...

    By default the script implements move files, but it is possible to copy them with the option -c, --copy.

    It is posible to include/exclude Perl modules with the option -M for those cases it you need to apply something very specific. It is similar to Perl's own option.

    With the -T or --transcode option it is possible to apply encoding over names. For example the following example works fine for filenames in Cyrillic with Perl 5.14 under Cygwin 1.7.25:

    file-rename -Tutf8 '$_ = ucfirst' -f ...

    Handling with filename component is enabled with the option -N, --filename-only. The is example (prepending filenames with some prefix):

    file-rename 's/^/old-/' -N ../*

    Verbosity, forcing and dry-run are implemented with the -v, -f and -n options, respectively. The long options are also available

    I have still never met the case of using the zero-terminated lines but implemented it with the options -z, -0, --null.

    The last thing I developed is renaming in loop with the option -r, --rename. With this option we can:

    Rotate files cyclically to left (resulting to file2 file3 file4 file1):

    file-rename --rename=rotate-left file1 file2 file3 file4
    Rotate files cyclically to right (resulting to file4 file1 file2 file3):
    file-rename --rename=rotate-right file1 file2 file3 file4
    Swap pair of files (swap nearest, resulting to file2 file1 file4 file3):
    file-rename --rename=swap file1 file2 file3 file4
    Flip the whole list of files (swap farthest, resulting to file4 file3 file2 file1):
    file-rename --rename=flip file1 file2 file3 file4

    The script lives in github. Below is the latest version to the moment of the writing.

Animated Heatmap
3 direct replies — Read more / Contribute
by Anonymous Monk
on Aug 10, 2019 at 08:52
New stable MCE 1.842 and MCE::Shared 1.842 releases
No replies — Read more | Post response
by marioroy
on Jul 21, 2019 at 23:13

    Update: Added results for Parallel::ForkManager 2.02. The results mentioned in the POD documentation ran slower due to an unaware background job at the time. I reran again on all 5 platforms.

    Dear fellow Monks,

    I am pleased to annouce MCE 1.842 and MCE::Shared 1.842 (both stable). MCE now includes MCE::Channel and MCE::Child recently.

    This weekend, added Parallel::ForkManager-like demonstration to the POD section in MCE::Child and MCE::Hobo. The results were captured on a Macbook Pro (late 2013 model - 2.6 GHz ~ 3.6 GHz with Turbo Boost).

    To run, one may direct standard output to :nul or /dev/null depending on the platform. Or better yet, I commented out the print line in the on_finish handler. Unfortunately, Parallel::ForkManager 2.02 suffers from memory leaks on the Windows platform ($^O eq 'MSWin32') and the reason why slower than Cygwin.

    These days, there are other ways and instead have workers persist (i.e. pull items from a shared queue or channel) or perhaps via MCE's input and chunking capabilities.

    Regards, Mario

2d field of view, vision algorithm in grid (ray casting)
1 direct reply — Read more / Contribute
by Discipulus
on Jun 24, 2019 at 15:05
    Hello community!

    who knows me is aware I'm writing a game (engine?) and I asked here for the precious monks wisdom about circular area in a coordinates grid (AoA).

    But now I'm progressing and I discovererd that the above illuminate function is not enough. I found a big resource of Roguelike_Vision_Algorithms and I choosed the simplest one (second example) and I ported it to Perl ( field_of_view sub in the below code ).

    Impressed by this shiny exemple I wrapped into an interactive program to show my proof of concept:

    Chatting in the perl irc channel daxim also implemented a semi-transparency feature I'd like to add to my game. Here daxim's patch (and a big thank to him):

    have fun!


    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Listener Crossword #4321 solitaire
No replies — Read more | Post response
by GrandFather
on Jun 21, 2019 at 06:19

    The Times newspaper features an occasional "The Listener Crossword" which is in fact a numerically based logic puzzle in the form of a crossword. A friend of mine introduced me to the genera with #4321 which is a puzzle of two parts. The first part consists of populating the playing grid with hexadecimal numbers. The second part consist of using the populated grid to play a game of solitaire which, when played correctly on a correctly constructed grid ends up spelling out three words. There is a certain amount of trial and error involved in finding the solution!

    So to aid playing the game in the second part of the puzzle I wrote the following script. The gameGrid is configured for a partial solution of the game. A feature of the code is that you can "save" the game state at any point then paste the saved gameGrid in place of the current grid to explore possibilities from that point.

    As far as I can tell developing tools of this sort is all part of the solution domain for the puzzle. They are very much one off puzzles as each "crossword" is a puzzle of a completely different nature, so it is very unlikely that this tool will be useful for another "Crossword Puzzle". But it is a cool use for Perl!

    Note that a few shortcuts have been taken in the code. In particular global variables are used, which I usually avoid. The rendered grid is not very pretty and the layout generally is rough, but good enough for the task at hand.

    Play consists of clicking on a "peg" (piece to be moved) then an "empty" cell ("_") skipping over one intervening piece. The skipped piece is removed and added to the "skipped" string. Moves can be undone back to the starting state. For instructions beyond these you will need to find the original puzzle instructions and create the starting grid.

    Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
Tk ASCII Draw on Canvas
4 direct replies — Read more / Contribute
by Discipulus
on Jun 03, 2019 at 06:57
    Hello folks!,

    another Tk CUFP from my part! It is working and is also a draft for a bigger project (you all know what I'm working on nowadays.. ;)

    This is an ASCII drawing program expoiting the best I'm able to from Canvas and their precious feature: tags.

    I left some commented code because I have some question in case some Tk expert has answers:

    -1 about binding modifiers: I planned the draw action when <Button1-Motion> is on: ie. when button 1 is pressed (modifier) and the pointer is moveing over the Canvas. No luck. The program below now uses <Control-Motion> and perhaps is even better (less mouse->less pain)

    -2 I noticed some strange behaviours with some key: aka sterling in Tk world and aka degree if I use one of them (now commented in the code) I get back a multichar: uppercase A with caret above plus the degree symbol, for instance.

    -3 I wonder how can I implement an export coordinates range in my Canvas: something like: when SHIFT modifier is on and Motion is on too I should tag tiles with something like selceted use a different color for them and haveing two buttons for export corrdinates and select nothing Seems this the right way?

    PS now you can draw fancy things like:


    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Coordinate validator
2 direct replies — Read more / Contribute
by timpoiko
on May 17, 2019 at 05:41
    Dear monks. Some years ago I write small program which can validate coordinates (locations on the Earth) from user input. I didn't to restrict format of input and I wanted support English as well as Finnish.
Flat File Database (random access indexing)
2 direct replies — Read more / Contribute
by erichansen1836
on May 04, 2019 at 10:16

    UPDATE Monday June 3, 2019... I tested filling a 128-GIG flat file (containing 137_438_953_472 bytes) with 68,430 complete copies of the KJV Bible, at 2_008_451 bytes/Bible. I was able to get 8 times as many records (over 2 billion records) when switching to variable-length delimited records where I additionally compacted the data by 50% more by storing the text as random seeded Word-to-Code key mapped text using 1, 2, and 3 character codes (1/4 million of them to randomly choose from) generated solely from the character set {A-Z, a-z, 0-9}. Additionally, I used SHA-2 (256) digital signature generation on 1 copy of the Bible (2_008_451 bytes) to compare against real-time digital signature generation each time a different copy of the Bible is accessed through the DB GUI front-end. A sector/block of 31,102 records, 2_008_451 bytes (a complete copy of the Bible) is read in by one READ STATEMENT through the front-end, and a digital signature generated on-the-fly to compare against the original. If a different signature is produced, an auto-correct of the database occurs from a backup image for the effected sector/block of records only. This happens faster than you can blink.

    UPDATE Monday May 6, 2019... I tested a 114-GIG Flat File for random access of its records and it works on Windows 7 Home Premium O/S with a NTFS (NT File System) using 64-bit ActiveState ActivePerl for Windows version/release 5.26.1. and the File I/O syntax: sysopen, sysseek, $tell=sysseek(FH,0,1), sysread, syswrite, and close. The Flat File had 7500 copies of the Bible in it (7500 copies of the Bible * 31,102 verses/Bible copy, and at a fixed-length record size of 528 bytes, and over 233 million records). I used a single 2-GIG SDBM index file to index the records of the 114-GIG Flat File. I would have indexed a full 128-GIG Flat File, but I hit the 2-GIG limit with the single SDBM file used for indexing. A 2nd SDBM file would be needed to index the records in a 128-GIG Flat File from the 114-GIG mark to the 128-GIG mark i.e. Bible copy 7501 through 8369.

Add your CUFP
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • 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, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            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.
  • Log In?

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

    How do I use this? | Other CB clients
    Other Users?
    Others wandering the Monastery: (7)
    As of 2020-02-18 13:38 GMT
    Find Nodes?
      Voting Booth?
      What numbers are you going to focus on primarily in 2020?

      Results (76 votes). Check out past polls.