Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

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
safe navigation in perl?
2 direct replies — Read more / Contribute
by morgon
on Dec 16, 2017 at 23:17

    recently I've done things like this (sorry, I am a bit drunk and too lazy to look up the actual code - but you get the gist...):

    my $subtree = $dom->find($whatever); $subtree->delete if $substree;
    And I was wondering if there was a better way to do this, some kind of Groovy "safe navigation" operator that would allow one to write:
    #pseudo-code - does not run!!! $dom->find($whatever)?->delete;
    i.e. a method-invocation that would check if the receicer was defined at all and simply does nothing if the receiver is undefined.

    I ask because something in the back of my mind tells me that I may have heard something to this effect at a conference, but as I said - I am a bit drunk...

    Many thanks!

Good CPAN project to give my kid some insight into development process?
2 direct replies — Read more / Contribute
by nysus
on Dec 16, 2017 at 13:51

    Over the upcoming Christmas break, I want to give my kid some direct insight into open source development and the process of software development. He may never end up being a software developer, but I'm thinking he should at least know the fundamentals and the tools involved in the process that is a big factor in our world.

    And now that I have finally learned myself how to contribute a CPAN module, I thought having him, under his name, contribute a module that anyone could download and modify would help get him excited.

    I don't want to pollute CPAN with something completely useless. So I'm wondering if anyone had a good idea for a simple module that did something fairly trivial but useful. He's into PC games and games on Steam and is big into League of Legends (which I know very little about). Maybe it could be related to that where it scrapes some info of the web and emails updates or something like that.

    Any thoughts or ideas are greatly appreciated!

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

Making the CPAN/GitHub updating process painless
3 direct replies — Read more / Contribute
by nysus
on Dec 16, 2017 at 11:09

    OK, finally created a CPAN module. I am now the most clueless Perl Developer.

    Getting something up and working on CPAN was fairly painless. I might not have known exactly what I was doing with commands like h2xs and make distcheck but blindly following the advice of some helpful documentation worked. I'm still left scratching my head over where the process pulled in my email address from (it's the wrong one) and the best way to get my GitHub repo linked on the left hand side of the metacpan page. I'll figure this out in due time.

    My question is, are there tools out there to this whole process as seamless and painless as possible? After making a couple of revisions to my module, I notice there are many repetitive tasks. There are a couple of dozen commands involved with making even a simple change to a POD file in the module. I'm imagining there must be script or suite of tools that:

    1) Had a simple config file where you put in all your PAUSE account and GitHub credentials and knew which repo on github your project was associated with

    2) Config file would also contain any info that goes into Makefile.PL and offer suggestions if you are missing data in your config or it can't figure it out from POD or module code

    3) Would automatically generate required CPAN files and upload them to CPAN for you

    4) Would push the changes automatically out to your github repo

    5) Take care of versioning information for you

    6) Generate necessary README files.

    So, for example, let's say I want to do something as fix an embarrassing typo to the POD that I wanted to push out immediately. First, I'd make the change. Then I'd be sure to change the version number in the code. Then I'd be sure to change the version number in the file for GitHub and the plain README file for CPAN. Then I'd change the name of directory the code is in for cpan. Then I'd issue (after looking them up first) my commands to generate the updated CPAN version. Then I upload my tarball to PAUSE (after transferring it to another machine that has a browser on it). Then I issue my git commands to commit the new code to GitHub. Then I check cpan and github to make sure I didn't screw something up.

    Instead of all that, ideally, I'd like just do something like this from the command line: update_module -v .22

    and be done.

    There seems like there are a patchwork of tools out there to do parts of these tasks but I'm not sure if there is anything that does it all. Can anyone point me in the right direction? Thanks.

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

read email-message
1 direct reply — Read more / Contribute
by Anonymous Monk
on Dec 16, 2017 at 05:02

    Hi everyone. I'm trying to write a script that reads the last message in the google mailbox, but i am failing. I am using the module Mail::IMAPClient. The code i use to try to get the actual message looks like this:

    $string = $client->message_string($msg);

    But when i print the string ($string), I get all sorts of information on the screen but not the actual message. I also tried:

    $string = $client->body_string($msg);

    But it gives the same result. I have been looking on the internet for answers but can't find something useful. I hope you can tell me.

hexadecimal division
9 direct replies — Read more / Contribute
by holandes777
on Dec 15, 2017 at 18:16

    Lift the veil of ignorance from my eyes

    I am trying to follow am LRC computation (Longitudinal CRC computation) and have hit a bump

    # Calculating the exclusive or of "202005" # V= X32 .XOR. X30 .XOR. X32 .XOR. X30 .XOR. X30 .XOR. X35 + = X05 my $command = '202005'; print "$command length=" . length($command) . "\n"; my $result = substr($command,0,1); for (my $i=1; $i<length($command); $i++) { my $c = substr($command,$i,1); print "$i) " . sprintf("%02X ", ord($result)) . " xor ". sprintf(" +%02X ", ord($c)); $result = $result ^ $c; print " gives " . sprintf("%02X ", ord($result)) . "\n"; } print sprintf("%02X ", ord($result)) . "\n"; if ( $result == "\x05" ) { print ":-)\n"; } else { print ":-(\n"; } print "====\n"; # THIS IS WHERE THE PROBLEM BEGINS: # Divide by X10: # Y = INT ( X05 / X10 ) = X00 my $dividend = $result; my $divisor = "\x10"; my $result2; #$result2 = int($dividend/$divisor); #print sprintf("%02X ", ord($result2)) . "\n"; # results in Illegal division by zero at line 22. # and this results in character zero, not NUL: $result2 = int(ord($dividend)/ord($divisor)); print sprintf("%02X ", ord($result2)) . "\n";

    What concept did I miss? Thank you.

    It has been pointed out I was noyt clear as to what I needed, and it is true! So allow me to clarify:

    The result of the xor-ing is correct according to the API doc: they expect X'05' and if you run the code we have a display of 05 which is 0x05. It is the next step, where we divide this 0x05 result by X'10' (0x10). The code says:<\p> $result2 = int($dividend/$divisor);

    what I expect is 5/16 converted to an int which is the NUL characted (0x00) which the API show as X'00'. The result I AM getting is 30 (0x30 or the ascii charated zero). This is where I need your help, on the last statement.

Using PerlApp or PAR with modules with data dependenciess
4 direct replies — Read more / Contribute
by Anonymous Monk
on Dec 15, 2017 at 11:59

    Hello monks

    I am trying to pack into an executable (exe) a simple perl script containing a module with data dependencies. I am failing. I am working with ActiveState/PerlApp, but I would like to be able to solve the problem even with Strawberryperl/PAR-PP. I am simply trying to pack the following script with one module.

    use Lingua::Sentence; my $splitter = Lingua::Sentence->new("en"); my $text = 'This is a paragraph. It contains several sentences +. "But why," you ask?'; print $splitter->split($text);

    The problem has to do imho with this line

    # Try loading nonbreaking prefix file specified in constructor my $dir = dist_dir('Lingua-Sentence');

    Once generated the exe there is no more dist_dir, I guess (?). Of course I can twik this line of the module code (for example setting a $dir of my choice (and give my client both exe and the files upon which the module depends), but I do not thing this is the right way to do it. What do you think? PS: this applies to all other modules using some sort of data/files in their module folder.

Appconfig module question
4 direct replies — Read more / Contribute
by hveneticus
on Dec 15, 2017 at 10:34

    I have to read a configuration file that contains lines like these ones:

    VAR=/path/to/ AMB=cer DIRSKE=${VAR}${AMB} SCRIPT=${DIRSKE}/

    After a search, I found that module Appconfig can be the right one. I've read its documentation more and more, but I think I don't really understand how it works (honestly, it is a bit harder to read). Consider also that I'm only a beginner in Perl. My problem is the variable named DIRSKE. Appconfig can expand the value as in a shell script, but I can't understand how do it when I have two of them in the same line.

    #!/usr/bin/perl use strict; use warnings; use AppConfig qw(:expand); my $config = AppConfig->new({ CASE => 1, GLOBAL => {EXPAND => EXPAND_ALL} }); $config->define("VAR=s"); $config->define("AMB=s"); $config->define("DIRSKE=s"); # Maybe this is wrong, but what else? $config->define("SCRIPT=s"); #read configuration file $config->file("./file.conf"); #some print print "Valore VAR -> ".$config->VAR()."\n"; print "Valore AMB -> ".$config->AMB()."\n"; print "Valore DIRSKE -> ".$config->DIRSKE()."\n"; print "Valore SCRIPT -> ".$config->SCRIPT()."\n";

    The output is:
    Valore VAR -> /path/to/ Valore AMB -> cer Valore DIRSKE -> Valore SCRIPT -> /

    I'd like to have something like:
    Valore VAR -> /path/to/ Valore AMB -> cer Valore DIRSKE -> /path/to/cer Valore SCRIPT -> /path/to/cer/

    Am I using the correct module?
    If yes, can I have a suggestion on how to do it?


sort HoH by second level values in specific order
6 direct replies — Read more / Contribute
by lener
on Dec 15, 2017 at 10:18
    Dear Monks, I have a Hash of Hashes, in which the first level contains the names of nodes and the second level contains values for their 'cores' and 'memory', it looks like this:
    $free_space = { "node1" => { "cores" => 12, "mem" => 200 }, "node2" => { "cores" => 12, "mem" => 500 }, ... }
    What I'd like to do is print it out while sorting by 'cores' (descendingly) first, 'memory' (descendingly) second and nodenames (ascendingly) last. So sort by cores, and if the number of cores is equal then sort by memory, if both are equal then sort lexicographically by the node names. It's supposed to look like this:
    cores memory node ----- ------ ---- 12 400 node456 12 400 node534 12 350 node23 11 500 node12 11 200 node3 10 900 node10
    I've tried doing it "manually" by creating a new HoHoA, where the 'cores' values are first-level keys, 'memory' values are second-level keys and the array holds the names of the nodes, then printing it simply by sorting level by level, like this:
    my %CoreMemNodes = (); #HoA <free_cores> -> <free_mem> -> (node1,node2 +,..) foreach my $node (keys %free_space) { push @{ $CoreMemNodes{$free_space{$node}{'cores'}}{$free_space{$no +de}{'mem'}} }, $node; } foreach my $free_cores (sort { $b <=> $a } keys %CoreMemNodes) { foreach my $free_mem (sort { $b <=> $a } keys %{ $CoreMemNodes{$fr +ee_cores} }) { foreach my $node (sort @{ $CoreMemNodes{$free_cores}{$free_mem +} }) { print "SORTED:$free_cores $free_mem $node\n"; } } }
    Is there a more efficient solution?
Array Plus Operator
2 direct replies — Read more / Contribute
by SleepyJay
on Dec 15, 2017 at 09:41
    I am deep in some legacy code (not written by me) that looks like this (it's surrounded by an if):
    @{ $self->bar || +[] }

    What's with that '+' in there? I mean, I get that it is usually used for disambiguation (e.g. @{ $self->bar || +shift }). But, what makes this plus needed?

    (I'm not a Perl beginner, but I have never seen Perl like this: is this a dumb question?)

Win32::Sound constants are weird
1 direct reply — Read more / Contribute
by Ralesk
on Dec 15, 2017 at 09:24

    Esteemed Monks,

    I was dumb and accidentally anded some flags instead of orring them at some point when I wrote the part of the software that employs Win32::Sound I would have found out way earlier, had SND_ASYNC not been 1, and so silently working as intended...

    Today I found the bug, replaced things with bitwise ors, and wondered why this could ever have worked before, and it seems that in weird situations (such as the flags being used in the argument list of Win32::Sound::Play), the constants behave completely non-DWIMly.

    So here's some examples:

    C:\>perl -E "use Win32::Sound; say Win32::Sound::SND_ASYNC; say Win32: +:Sound::SND_LOOP; say Win32::Sound::SND_NODEFAULT;" 1 8 2

    This should mean that SND_ASYNC and (as I erroneously wrote) SND_NODEFAULT is 0, right? 1 & 2 is zero, we all know that. Those two orred together is 3.

    ... Win32::Sound::Play($filename, Win32::Sound::SND_ASYNC & Win32::Sound:: +SND_NODEFAULT); ...

    Lo and behold, that thing there has SND_ASYNC set. No, it's not a precedence issue, it would be the same if the bit construct were surrounded by an extra set of parentheses.

    C:\>perl -E "use Win32::Sound; say Win32::Sound::SND_ASYNC & Win32::So +und::SND_NODEFAULT;" 1 C:\>perl -E "use Win32::Sound; $x = (Win32::Sound::SND_ASYNC & Win32:: +Sound::SND_NODEFAULT); say $x" 1 C:\>perl -E "use Win32::Sound; say (1 & 2);" 0 C:\>perl -E "use Win32::Sound; say ('1' & '2');" 0 C:\>perl -E "use Win32::Sound; my $as = Win32::Sound::SND_ASYNC; my $n +d = Win32::Sound::SND_NODEFAULT; say $as & $nd;" 0 C:\>perl -E "use Win32::Sound; my @as = Win32::Sound::SND_ASYNC; my @n +d = Win32::Sound::SND_NODEFAULT; say @as; say @nd; say (@as & @nd);" 1 2 1

    There it is & requires scalar values to bitwise and, so takes the length of the two list context return values, which is 1 for each because each is a one element array. Or, if anything, forcing list context on these guys seems to at least replicate the error no clue why they'd be in list context there in the original usage!

    This doesn't, however, explain why it works out of the box with |, where the list context hack doesn't:

    C:\>perl -E "use Win32::Sound; my @as = Win32::Sound::SND_ASYNC; my @n +d = Win32::Sound::SND_NODEFAULT; say @as | @nd;" 1 C:\>perl -E "use Win32::Sound; $x = (Win32::Sound::SND_ASYNC | Win32:: +Sound::SND_NODEFAULT); say $x" 3

    The only question I have is just: why?

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 lurking in the Monastery: (2)
    As of 2017-12-17 09:25 GMT
    Find Nodes?
      Voting Booth?
      What programming language do you hate the most?

      Results (462 votes). Check out past polls.