Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Seekers of Perl Wisdom

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

If you have a question on how to do something in Perl, or you need a Perl solution to an actual real-life problem, or you're unsure why something you've tried just isn't working... then this section is the place to ask. Post a new question!

However, you might consider asking in the chatterbox first (if you're a registered user). The response time tends to be quicker, and if it turns out that the problem/solutions are too much for the cb to handle, the kind monks will be sure to direct you here.

User Questions
Image Conversion: SVG to PNG
3 direct replies — Read more / Contribute
by kcott
on Apr 23, 2017 at 04:12

    I'm generating some fairly basic SVG files and will want to convert them to PNG format. Each SVG file will be used to create a number of PNG files of different sizes (it's only a size change; aspect ratio, colours, etc. all remaining the same). I'd also like the solution to be as portable as possible (at least working on *nix and MSWin platforms). I've included my investigations so far, my questions are at the end.

    Here's the test SVG file, test.svg, that I've been playing with and referenced in various examples below:

    I had the ImageMagick® convert utility available, so I tried that first. This seemed to work fine; I tested at two reduced sizes:

    $ convert test.svg -resize 16x16 test016.png $ convert test.svg -resize 32x32 test032.png

    However, when I looked into installing the Image::Magick module for use in my scripts, I was amazed to find only failures (UNKNOWN: 1276; FAIL: 412) in the "CPAN Testers Matrix: PerlMagick 6.89-1". I followed the links to the previous five releases, thinking maybe there was some problem with just 6.89-1; unfortunately, all were exactly the same except for 6.86 which had just one PASS amongst hundreds of failures. I don't know if that's some sort of reporting error. I chose not to follow that path any further.

    I had previously, successfully installed GD, so I decided to look into that further. I browsed the GD::Convert, GD::SVG and SVG modules. While this looked like it might work (after a fashion), it didn't seem particularly straightforward and even the documentation says:

    "GD::SVG may provide a short-term solution while scripts are re-written to enable more direct output of SVG."

    There were also too many caveats for my liking, so I abandoned this avenue also.

    SVG has a small section on converting to PNG. It mentions Image::Magick and also Image::LibRSVG. I hadn't heard of this other module before and decided to try it. It installed without any fuss and usage was totally uncomplicated:

    $ perl -wMstrict -MImage::LibRSVG -e 'Image::LibRSVG::->new()->convert +AtSize("test.svg", "test016.png", 16, 16)' $ perl -wMstrict -MImage::LibRSVG -e 'Image::LibRSVG::->new()->convert +AtSize("test.svg", "test032.png", 32, 32)'

    Not only that, but it produced PNG files that were substantially smaller than those produced by convert (without any noticable degradation of image quality; in fact, the 16x16 one looked a little crisper). I had renamed the files I produced earlier (*.png to *_via_convert.png), here's a size comparison:

    -rw-r--r-- 1 ken staff 678 Apr 23 13:03 test.svg -rw-r--r-- 1 ken staff 124 Apr 23 14:01 test016.png -rw-r--r-- 1 ken staff 316 Apr 23 13:10 test016_via_convert.png -rw-r--r-- 1 ken staff 186 Apr 23 13:57 test032.png -rw-r--r-- 1 ken staff 415 Apr 23 13:11 test032_via_convert.png

    My only concerns with Image::LibRSVG are its age (no update in 11 years) and no successful builds on MSWin. The age may not be a huge issue: SVG has been stable for many years and, as an interface to the librsvg library, it may rely on that library being current, especially if its API hasn't changed. I randomly checked many failures on "CPAN Testers Matrix: Image-LibRSVG 0.07": all (going back to Perl 5.10) were UNKNOWNs, and all failed due to the librsvg library not being found — this may not be a problem either.

    So, after all that, I have these questions:

    • Has anyone successfully installed Image::LibRSVG on an MSWin platform? If so, were there any major hurdles to overcome? [A Super Search for Image::LibRSVG produces no results.]
    • Does anyone have any suggestions for other modules which I could try for this conversion task?

    — Ken

Parsing Boolean expressions
3 direct replies — Read more / Contribute
by Anonymous Monk
on Apr 22, 2017 at 22:22

    Is there a readily usable library to parse Boolean expressions like below:

    Y = A + (B*C) Y = A + (B' + (C*D)') Y = A*(B*(C'+D)')

    Thanks in advance.

how to fork & join in tk?
2 direct replies — Read more / Contribute
by redss
on Apr 22, 2017 at 18:40
    Hi Monks,

    I want a Tk program to perform a subroutine that takes a few seconds when a button is pushed. But I don't want to wait on the the subroutine before returning control to the mainloop. When the subroutine finishes I want it to update the title on the button.

    So in the below example, when the button is clicked, I want the button label to immediately update to "step two", then whenever the function finishes, to update to step 3, rather than tie up control while waiting for the function to finish.

    How can I do this?

    use Tk; + + $main = MainWindow->new(); + + $button = $main->Button(-text => "step one", -command => \&fun); + $button->pack(); + + MainLoop(); + + sub fun { $button->configure(-text => "step two" ); sleep 1; $button->configure(-text => "step three" ); }
add missing elements and remove duplicates....and some more questions.
5 direct replies — Read more / Contribute
by pritesh_ugrankar
on Apr 22, 2017 at 18:13

    Hi Monks,

    I've been here since past few weeks and gleaned a lot of knowledge here. I recently started getting back to Perl, the only language that I know, for fun and may be more than fun in future. I had last week posted a question anonymously and got astounding replies and encouragement to post questions here with my login name. Hence this time, I have logged in with my name and asking questions.

    I was asked to come up with the following without using sorting.

    Given a random series of numbers, which may include hex numbers, write a script that will remove the duplicates, fill in the gaps if any, and print the numbers in a sequence. Do not use hash, do not use any existing libraries, but "do it yourself" as much as you can.

    So I came up with this

    $ more /home/pritesh/ use warnings; use strict; my @arr = (10,10,20,0x47,1,30,45,45); sub do_it_all { my $biggest = shift @_; foreach my $num (@_) { if ($num > $biggest) { $biggest = $num; } } my $smallest = shift @_; foreach my $smallnum (@_) { if ($smallnum < $smallest) { $smallest = $smallnum; } } my @unique = ($smallest..$biggest); print "@unique\n"; } &do_it_all(@arr);

    Which prints the following.

    $perl 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 +7 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 5 +0 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

    I was given the following feedback.

    That I did not try to address the issue, but circumvented the issue by simply taking a shortcut of finding the smallest number and then the biggest number and generating the numbers.

    That I should have done more research and come up with a better solution which would check each number with the preceding one and done some better programming.

    This is going to sound funny, but I was told not to use Linux Mint as it is not a "real Linux distro" and that people who do programming/scripting do not use Mint/Ubuntu as they are not "up to the mark". This was the remark that frankly made me suspicious of his line of thought.

    I have not till date seen such remarks here by any of the esteemed monks. Can you please shed more light on any of the points mentioned above? Is this kind of shortcuts considered a "non programmer's approach" to problem solving?

    Thinkpad T430 with Ubuntu 16.04.2 running perl 5.24.1 thanks to plenv!!
Where does the 6th process come from? [SOLVED]
4 direct replies — Read more / Contribute
by karlgoethebier
on Apr 22, 2017 at 10:24

    Good day all,

    this is just another useless waste of time for fun and perhaps learning.

    I spawn 4 processes but ps shows 6. But it should be 5, right?

    #!/usr/bin/env perl # "When I first started hobo'in, # I took a freight train to be my friend" # -John Lee Hooker # use strict; use warnings; use MCE::Hobo; use MCE::Shared; use feature qw(say); # use Sereal (); use MCE::Mutex; say "procs at start:\n", procs(); our $mutex = MCE::Mutex->new; # say $mutex->impl(); my $result = MCE::Shared->array(); my $foo = MCE::Hobo->create( \&task, "foo" ); my $bar = MCE::Hobo->create( \&task, "bar" ); my $nose = MCE::Hobo->create( \&task, "nose" ); my $cuke = MCE::Hobo->create( \&task, "cuke" ); my @hobos = MCE::Hobo->list(); say "spawned hobos:"; for (@hobos) { if ( $_->is_running() ) { say 'pid: ', $_->pid(); } } say 'pending hobos: ', MCE::Hobo->pending(); say "procs at pending:\n", procs(); $_->join() for @hobos; say "procs after join:\n", procs(); say "result:"; say for @$result; sub task { our $mutex; $mutex->lock; $result->push(shift); $mutex->unlock; } sub procs { my $procs = qx(ps aux | grep [p]erl); $procs =~ s/ //g; chomp $procs; $procs; } __END__ karls-mac-mini:MyAdaModule karl$ ./ procs at start: karl254417,30,124421128816s000S+6:03pm0:00.07perl./ spawned hobos: pid: 2549 pid: 2550 pid: 2551 pid: 2552 pending hobos: 4 procs at pending: karl254417,30,124421129264s000S+6:03pm0:00.08perl./ karl25520,00,000s000Z+6:03pm0:00.00(perl) karl25510,00,000s000Z+6:03pm0:00.00(perl) karl25500,00,000s000Z+6:03pm0:00.00(perl) karl25490,00,000s000Z+6:03pm0:00.00(perl) karl25480,00,024421123116s000S+6:03pm0:00.00perl./ procs after join: karl254417,30,124421129264s000S+6:03pm0:00.08perl./ karl25480,00,024421123136s000S+6:03pm0:00.00perl./ result: foo bar nose cuke

    Update: Added more debugging output

    Thanks for any hint and sorry if i missed something essential.

    Update 2:

    Regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

    Furthermore I consider that Donald Trump must be impeached as soon as possible

How can one create a text file in the subfolder of a folder?
4 direct replies — Read more / Contribute
by supriyoch_2008
on Apr 22, 2017 at 05:33

    Hi Perlmonks,

    My interest is to create a text file z.txt inside a subfolder y of the main folder x. I want to write in the text file using a file handle like $fh. I searched for perl examples online but did not find one which can solve my problem. I have written a script which creates folders x and y and not the file. The result in cmd shows "Cannot open file 'x/y/z.txt'". I welcome suggestions from the perlmonks to sort out this problem.

    Here goes my script

    #!/usr/bin/perl use strict; use warnings; my $x='x'; my $y='y'; my $dirname = "$x/$y"; my @folders = split /\/|\\/, $dirname; map {mkdir $_; chdir $_;} @folders; # Print output to a Text File: my $output="$dirname/z.txt"; open (my $fh,">",$output) or die "Cannot open file '$output'.\n"; print $fh "\n It's ok.\n"; close $output; print "\n Program is over.\n"; exit;

    Here goes the result of cmd:

    Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users>cd d* C:\Users\Desktop> Cannot open file 'x/y/z.txt'. C:\Users\Desktop>
my versus our, why is my slower when script ends (global cleanup)
1 direct reply — Read more / Contribute
by marioroy
on Apr 21, 2017 at 21:51

    Respected Monks,

    On Mac OS X and Linux (not tested on other Unix platforms), there appears to be extra overhead by Perl prior to the script exiting for variables declared with my. The extra time is noticeable after seeing the "end" output.

    Why does Perl have this odd behavior during cleanup?

    use strict; use warnings; $| = 1; my $size = 2e6; my $data = [ 'AGCTCGTTGTTCGATCCA', 'GAGAGATAGATGATAGTG', 'TTTT_CCCC', 0 ]; print "begin\n"; my %barcode_hash = map { $_ => $data } 1 .. $size; print "end\n";

    There is practically no delay after seeing "end" if I declare the variable with our.

    ... our %barcode_hash = map { $_ => $data } 1 .. $size; ...

    I made a script to capture the running time, helpful on Windows. Unix has time command and shell builtin time.

    use strict; use warnings; use Time::HiRes 'time'; my $start_time = time; system(@ARGV) == 0 or die "\"@ARGV\" failed with error: $?"; printf "%0.03f seconds\n", time - $start_time;


    perl perl my %big_hash: 2.726 seconds our %big_hash: 1.351 seconds

    Thank you, karlgoethebier for this enlightenment. I do not understand what Perl is doing during cleanup. Has anyone encountered this behavior? I tested on Windows and is nothing like seen on Mac OS X and Linux.

    Thanks, Mario

incorporate HTML coding in a Perl program
4 direct replies — Read more / Contribute
by Anonymous Monk
on Apr 21, 2017 at 14:03
    I have found an HTML script which implements a dropdown list. I would like to incorporate the script into a Perl program so that I can create variables in Perl that can be interpolated in the HTML construction. I have tried using a HERE doc but the Perl coding shows up on the HTML page. Is this possible?
    <!DOCTYPE html> <html> <head> <style> .dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropbtn:hover, .dropbtn:focus { background-color: #3e8e41; } .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; overflow: auto; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a { color: red; padding: 12px 16px; text-decoration: none; display: block; } .dropdown a:hover {background-color: #f1f1f1} .show {display:block;} </style> </head> <body> <h2>Clickable Dropdown</h2> <p>Click on the button to open the dropdown menu.</p> <div class="dropdown"> <button onclick="myFunction()" class="dropbtn">Dropdown</button> <div id="myDropdown" class="dropdown-content"> <a href="#percent_cover">Percent Cover</a> <a href="#about">About</a> <a href="#contact">Contact</a> </div> </div> <script> /* When the user clicks on the button, toggle between hiding and showing the dropdown content */ function myFunction() { document.getElementById("myDropdown").classList.toggle("show"); } // Close the dropdown if the user clicks outside of it window.onclick = function(event) { if (!'.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content" +); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } </script> </body> </html>
text alignment
3 direct replies — Read more / Contribute
by Anonymous Monk
on Apr 21, 2017 at 13:13

    Hi I am new to Perl and am using Padre IDE. How do I align the text in a print statement

    print "How do I align this statement so that it does not look like a r +un on sentence and take up the whole screen? \n";
Method for reducing tedium of transferring object properties to scalars
6 direct replies — Read more / Contribute
by nysus
on Apr 21, 2017 at 12:01

    Greetings fellow Monks. It's been a few weeks. I'm happy to report I'm making good progress on a fairly extensive project of mine thanks to all the kind help found here.

    So one thing that is annoying me right now is the process of populating scalars with object properties to make code more readable. For example:

    sub function { my $self = shift; my $val1 = $self->get_value1; my $val2 = $self->get_value2; my $val3 = $self->get_value3; print "Values: $val1, $val2, $val3"; }

    For me, I find transferring object properties to scalars is less error prone and makes code easier to read than something like: print "Values: " . $self->get_value1 . ', ' . $self->get_value2 . ', ' . ', ' . $self->get_value3"; or printf "Values: %s, %s, %s", $self->get_value1, $self->get_value2, $self->get_value3";

    I know it's possible to do print "${\$self->get_value}" but that is just god awful.

    Using scalars is also useful if I have to use a property several times in the same block of code or if there are many object properties to keep track of. It saves a lot of typing and, again, makes the code easier to read. But it still can be super annoying to create these scalars. I'm wondering if there might be some useful trick out there that will spare me the oh so tedium of creating scalars for my object properties. Thanks.

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate";
    $nysus = $PM . ' ' . $MCF;
    Click here if you love Perl Monks

Add your question
Your question:
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 all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others rifling through the Monastery: (4)
    As of 2017-04-23 11:35 GMT
    Find Nodes?
      Voting Booth?
      I'm a fool:

      Results (430 votes). Check out past polls.