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

The Monastery Gates

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

Donations gladly accepted

If you're new here please read PerlMonks FAQ
and Create a new user.

New Questions
Videos from LPW 2016?
No replies — Read more | Post response
by LanX
on Apr 29, 2017 at 15:59
HASH value error
2 direct replies — Read more / Contribute
by pdahal
on Apr 29, 2017 at 01:58
    I am a beginner in perl. I need to parse an XML file and store the results into CSV file. The problem I am facing is I am getting the output like "HASH(0x3de3350)" instead of PubMed IDs like "16466327" in CSV file. How can i handle this?
Array of variables
7 direct replies — Read more / Contribute
by Michael W
on Apr 27, 2017 at 11:38
    my @Variables = ( $Map_Request_Date,$Map_Due_Date,$Map_Cutover_Date,$ +Map_Complete_Date,$Map_Approved_Date); foreach $Date_Ref (@Variables) { print $Date_Ref; $Date_Ref =~ s/ +/ /; #When day is a single digit it creates two wh +ite spaces ($Month,$Day,$Year,$Time)= split / /, $Date_Ref,4; my %Months = ( 'Jan' => '01', 'Feb' => '02', 'Mar' => '03', 'Apr' + => '04', 'May' => '05', 'Jun' => '06', 'Jul' => '07', 'Aug' + => '08', 'Sep' => '09', 'Oct' => '10', 'Nov' => '11', 'Dec' +=> '12' ); if (length($Day) == 1) {$Day = "0$Day";}#Add 0 to the front of sing +le digit days @Variable[$X]=$Year."-".$Months{$Month} ."-" . $Day ; $X=$X+1; }

    Working on a date issue from sql to html format

    previous only used an array of variables to read from

    this time I want to place the value back into the array of variables

    this line: @Variable$X=$Year."-".$Months{$Month} ."-" . $Day ;

    all the code works until I try to write the new variable back in

Randomly reassign hash keys
6 direct replies — Read more / Contribute
by cormanaz
on Apr 26, 2017 at 12:47
    Good day bros. I would like to create a hash, then randomly reassign the keys (to support a randomization test). I know I can get a shuffled list of keys with
    use List::Util qw(shuffle); ... foreach my $k (shuffle keys %foo) { ... }
    but accessing that would leave the keys associated with the same values. I want to randomly reassign the keys to different values already in the hash. So if the original was
    %hash = ( "a" => 1, "b" => 2, "c" => 3, "d" => 4 };
    I could end up with
    %hash = ( "c" => 1, "d" => 2, "a" => 3, "b" => 4 };

    I can imagine how to do that in an inelegant way, but was wondering if there is an elegant way.

Malformed JSON Error Piwigo
1 direct reply — Read more / Contribute
by kiteboywales
on Apr 26, 2017 at 09:43

    Hi all - I looking for advise regarding the following error

     malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "<br />\n<b>Warning</...") at /usr/share/perl5/JSON.pm line 171

    Hope you dont mind asking - I get this error when uploading to something called PIWIGO. An online image gallery. The perl script itself is available here http://piwigo.org/ext/extension_view.php?eid=606

    While images do upload fine I get the above error and then the uploading stops. If I run the script again it can be seen that the image it seemed to fail on did upload and then it moves onto the nexxt image and then again the error pops up again.

    If someone has any ideas that would be great....thanks for any advice

Re-dimensioning an HTML table with Perl ?
12 direct replies — Read more / Contribute
by TheDonald
on Apr 25, 2017 at 13:08
    I'm staring down the abyss of something that I would rather not do manually. So it occurred to me that Perl is probably just the sort of thing for such a random requirement. What I need to do is "re-dimension" (what is the correct word ?) an HTML table. The table is currently 5x12, and I want to turn it into, say, 7x9. The thought of lifting and shifting dozens of cells by hand is filling me with dread ! I've no ideas where to start in terms of automating this, let alone how to code it (I've only recently joined the long road to Perl wisdom !).
"my" declaration problem
6 direct replies — Read more / Contribute
by Hosen1989
on Apr 25, 2017 at 07:17

    Dear ALL,

    I was debug some old dirty script of mine (which without strict nor warnings ^_^), and faced this issue:

    As you can see in case(1), variable $me had been declared more than once, and to output of this script is: []

    #----------[ CASE(1) ]----------# my $v_place = 'home'; my $me = 'moving'; my $me = 'at home' if($v_place =~ m/^home/); my $me = 'at work' if($v_place =~ m/^work/); print "[$me]"; __END__ output: [] #-------------------------------#

    But after correct the declaration problem as in case(2), we got the correct output: [at home].

    #----------[ CASE(2) ]----------# my $v_place = 'home'; my $me = 'moving'; $me = 'at home' if($v_place =~ m/^home/); $me = 'at work' if($v_place =~ m/^work/); print "[$me]"; __END__ output: [at home] #-------------------------------#

    Now,can any monk explain me just what happen here?

    BR

    Hosen

'Missing version identifier' error while connecting to Hive, using Thrift module of Perl
1 direct reply — Read more / Contribute
by Omnitrix
on Apr 25, 2017 at 07:03

    I tried to connect to Hive using Thrift::API::HiveClient2. Wrote the following:

    #!usr/bin/perl use strict; use warnings; use Thrift::API::HiveClient2; my $port = 12345; my $host = '123:456:789:987'; my $client = Thrift::API::HiveClient2->new( host => $host , port => $port, ); $client->connect() or die "Failed to connect\n"; my $query = "hive query;"; my $rh = $client->execute($query);

    An I am getting the following error->

    Thrift::TException error: Missing version identifier (code 0) (in cl +eanup) Thrift::TException error: Missing version identifier (code 0) at (eval + 144) line 31.

    My Hive client is HiveClient2. What am I missing?

Debugging Perl Mojolicious application
4 direct replies — Read more / Contribute
by sduggal
on Apr 24, 2017 at 02:58

    Hi Monks!

    I have a Perl Mojolicious framework application/web app on Windows. It is using the development server for now. Does anyone have experience on debugging in such an environment using an IDE? I want to use breakpoints and step through the code. Please guide me on the IDE in case anyone has been in the same boat.

Image Conversion: SVG to PNG
6 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

how to fork & join in tk?
4 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" ); }
New Meditations
Assigning to Hash Values (updated)
No replies — Read more | Post response
by haukex
on Apr 28, 2017 at 12:49

    The thread "Randomly reassign hash keys" got me thinking about this one. The values doc says:

    Note that the values are not copied, which means modifying them will modify the contents of the hash.

    This means that $_++ for values %hash; will modify the original hash values, and the following (based on this AM post) will assign to the values of the hash:

    sub { @_[0..$#_] = qw/r s t/ }->(values %hash);

    The above work because both the foreach loop variable and the elements of @_ are aliases to the original scalars. The slice in the second example is necessary, since @_ = ... would clobber the array and remove the aliasing, instead of assigning to its elements.

    However, values itself is not lvalue, meaning that values(%hash) = qw/a b c/; won't work. Neither will (values(%hash))[0] = 'a';.

    Here's my "invention", which I present as a curiosity rather than a suggested solution. It makes use of Lvalue subroutines and Prototypes. The parens on the left are necessary for the sub to be called in list context.

    sub lvalues (\%) : lvalue { values %{$_[0]} } (lvalues %hash) = qw/i j k/; # works!

    Since the order of the values returned by values is random, this probably isn't particularly useful other than in the context of the thread I mentioned above:

    (lvalues %hash) = shuffle values %hash;

    Updates 1&2: However, note that repeated calls to (lvalues %hash) = values %hash; will only "randomize" the values once, and on older Perls the order won't be very "random" at all apparently not randomize at all, I would guess because the order of the returned values is not randomized between the calls to values. Some interesting reading on the topic: Re^2: setting PERL_PERTURB_KEYS & PERL_HASH_SEED in a perl file and Re^2: Curious: are anon-hashes in random order?

    Minor updates for clarification.

Big thank you to the Perl community.
2 direct replies — Read more / Contribute
by Anonymous Monk
on Apr 24, 2017 at 06:21

    Revered Monks and dwellers of this venerated place,

    I've been here for approximately two months now and I have no words to express my gratitude. The level of information shared here is amazing. The knowledge of the monks just blows my mind. Answers given here are of very high quality and I've come to realize that PerlMonks is the best place to learn Perl

    Just wanted to take a moment to extend a heartfelt "Thank You" to all you knowledgeable and helpful folks here. Spending a few minutes here is far more enriching and fulfilling. The suggestions and advice given by you Monks has literally shaved off hours of time. I started with Perl due to its practicality and immediacy with which it naturally lends itself to real life problem solving, but now, I have started falling in love with this amazing language, all thanks to you folks.

    This language deserves so much more attention and respect than it gets. All this talk of "Perl is Dead" now simply makes me wonder what the hell is going wrong with folks. This language will never die, because 1) its a pragmatic, practical and amazing language and 2)PerlMonks.

New Cool Uses for Perl
Prima + MCE::Hobo demonstration
2 direct replies — Read more / Contribute
by marioroy
on Apr 29, 2017 at 03:03

    Respected Monks,

    Starting with MCE 1.828 and MCE::Shared 1.825, running MCE with Prima is possible. The following is based on the Tk + MCE::Hobo demonstration (2nd example in the post). I tested Prima + MCE on Linux using CentOS 7.x and Windows with Strawberry Perl 5.22.x.

    use strict; use warnings; use MCE::Hobo; use MCE::Shared; use Prima qw( Application Buttons Label ); my $que = MCE::Shared->queue(); my $msg = MCE::Shared->scalar("Start"); my $hobo = MCE::Hobo->create("bg_task"); my $wm = Prima::MainWindow->new( size => [ 250, 200 ], text => 'Hello world!', onDestroy => \&quit ); my $lbl1 = Prima::Label->create( owner => $wm, size => [ 220, 50 ], text => 'Prima + MCE Demo', alignment => ta::Center, valignment => ta::Middle, pack => {} ); my $btn1 = Prima::Button->new( owner => $wm, size => [ 120, 50 ], text => $msg->get, onClick => \&fun, pack => {} ); my $btn2 = Prima::Button->new( owner => $wm, size => [ 120, 50 ], text => 'Quit', onClick => sub { $::application->close }, pack => {} ); my $timer = Prima::Timer->create( timeout => 100, onTick => sub { $btn1->set( text => $msg->get ); } ); $timer->start; run Prima; sub fun { $que->enqueue("some event"); return; } sub quit { $timer->stop; $hobo->exit->join; $::application->close; } sub bg_task { while ( my $event = $que->dequeue ) { $msg->set("Step One"); sleep 1; $msg->set("Step Two"); sleep 1; $msg->set("Step Three"); } }

    So that the quit function isn't called twice, I'm only calling $::application->close inside the Quit handler. That closes the window which then triggers the MainWindow's onDestroy handler.

    Regards, Mario

Parallel::ForkManager + MCE::Shared demonstration
1 direct reply — Read more / Contribute
by marioroy
on Apr 23, 2017 at 22:26

    Respected Monks,

    In preparation for the upcoming MCE 1.828 and MCE::Shared 1.825 releases, am testing various modules with MCE::Shared. One of which is Parallel::ForkManager.

    Discipulus introduced me to zentara recently. zentara am pleased to meet you. Discipulus, imho, folks may choose any parallel module of their liking. It doesn't need to be MCE and the reason for this thread. I like Parallel::ForkManager too.

    Some time back, zentara wrote a Parallel::ForkManager + IPC::Shareable demonstration. Fast forward 2.5 years and here's another way. MCE::Shared provides users of Parallel::ForkManager with threads-like sharing capabilities. Below is zentara's example updated with MCE::Shared bits.

    Not to worry, MCE::Shared performs reasonably well.

    #!/usr/bin/perl # Based on Parallel::ForkManager + IPC::Shareable by zentara. # Found here: http://www.perlmonks.org/?node_id=1104697 use strict; use Parallel::ForkManager; use MCE::Mutex; use MCE::Shared; my $mutex = MCE::Mutex->new(); my $parent_share = tie my %final_parent_hash, 'MCE::Shared'; my $fork_manager = new Parallel::ForkManager(5); $fork_manager->set_waitpid_blocking_sleep(0); foreach my $child ( 1 .. 10 ) { my $pid = $fork_manager->start($child) and next; # Optional, to have the shared-manager assign a data channel. # Helpful when involving heavy IPC usage, not the case here. # Increase 20 to 2000 to see perf-increase from calling ->init. MCE::Shared->init(); for my $id ( 1 .. 20 ) { my $key = $child . '-' . $id; # $mutex->lock; # mutex not necessary when storing unique keys # $parent_share->set($key => qq{|Kid $child pushed $id}); # OO $final_parent_hash{$key} = qq{|Kid $child pushed $id}; # $mutex->unlock; } $fork_manager->finish($child); } print "Waiting for Children...\n"; $fork_manager->wait_all_children; foreach my $child ( 1 .. 10 ) { for my $id ( 1 .. 20 ) { my $key = $child . '-' . $id; if (! exists $final_parent_hash{$key} ) { print "Missing data for Kid $child , data $id\n"; } else { print "$key = $final_parent_hash{$key}\n"; } } }

    The following are recommended modules for MCE::Shared.

    ## MCE::Shared 1. Sereal::Decoder 3.015+ 2. Sereal::Encoder 3.015+ 3. Sereal (ok for completeness, but MCE::Shared doesn't load this) ## MCE::Shared applies to Condvar, Handle, and Queue 1. IO::FDPass 1.2+

    Q. Why is Sereal beneficial?

    A. The main reason is for extra performance. To ensure minimum memory consumption, there's no reason to load the Storable module if Sereal is available in Perl. This is handled transparently.

    Q. Why is IO::FDPass beneficial?

    A. Being able to construct a shared condvar, handle, or queue while the shared-manager is running greatly adds to the ease-of-use. These involve handles behind the scene. Basically, am able to send the relevant fd descriptors to the shared-manager. Without FDPass, one must be careful to construct Condvar, Handle, and Queue first before other shared objects and later starting the shared-manager manually. Note: MCE and MCE::Hobo starts the shared-manager if not already started.

    Q. What is MCE::Shared->init all about?

    A. For MCE, MCE::Hobo, and threads (via CLONE), MCE::Shared->init() is called automatically. It assigns the worker 1 of 12 data channels for use during IPC. Calling init is totally optional. If the worker is sending data one time, probably not necessary. On the other hand, if doing lots of IPC, then yes worth it.

    For further reading, see also this thread made by karlgoethebier or this reply regarding performance characteristics (TIE and Mutex or OO). Basically, performance is possible. And so is fun.

    Regards, Mario.

New Monk Discussion
The Cookies account
3 direct replies — Read more / Contribute
by Lady_Aleena
on Apr 26, 2017 at 04:47

    A little over four years ago, I created the Cookies account for fun. I was known for my chatterbox antics with cookies; so on April Fools 2013, I decided to have some fun. Two years ago I went in for surgery, which is scary. I was thinking something could happen, and Cookies would be left without someone to maintain the account.

    Some users still play with the buttons from time to time. I would not want the account to die just because I did. So, if anything happened to me, would there be someone who would be willing to take over this very silly account?

    P.S. I am always willing to add more flavors and options to the account. Just let me know.

    P.P.S. This thread can be for anything related to the Cookies account that might merit general discussion, too. 8)

    No matter how hysterical I get, my problems are not time sensitive. So, relax, have a cookie, and a very nice day!
    Lady Aleena, the Cookie Lady
Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2017-04-29 20:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I'm a fool:











    Results (534 votes). Check out past polls.