Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

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
[OT] Mathematical photographers that program (Perl)? (Updated.)
1 direct reply — Read more / Contribute
by BrowserUk
on Mar 25, 2017 at 04:33

    Update: It turns out that there is something weird with the image I chose as an example (picked from an online image search for its size focus and apparent normality to the camera lens), in as much as, the thread angle (the inclusive angle between the faces of adjacent turns of the threads), is as near as I can measure 90°. That's weird because none of the defined standard threads use a 90° thread angle. Metric and Unified are 60°; BSW are 55° & BA are 47.5°. So don't base too much on that image; I'll swap the link for one I know is good once I find it.

    Update2: Image now updated with what I am pretty confident are standard M8x1.0 threaded nuts and bolts.

    If you look at this image, the extreme close-up nature of the photo, the close proximity of the lens to the subject and parallax mean that you can see the underside of the heads of the bolts, but the end of the bolts is not visible.

    My question is: Is there a way to determine the central axis of the lens in this photo?

    Basically what I would like to do is, assuming (for now) that the plane of the photograph is normal to the lens that took it, draw a red cross on the image at the point the central axis of the lens intersects that plane.

    Firstly, is there enough information in the photograph to make that determination?

    And if so, can a program then be written to automate that process. (But I'm not asking anyone to attempt the latter, just looking for clues how to approach the problem.)

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". The enemy of (IT) success is complexity.
    In the absence of evidence, opinion is indistinguishable from prejudice.
RFC and Questions regarding a module to automate and centralize infrastructure administration
4 direct replies — Read more / Contribute
by cbeckley
on Mar 24, 2017 at 19:57

    I've written a module, nascent, that makes it a little easier to execute a list of commands on a group of servers. Basically I create an array of servers, which I refer to as contexts in the code, each of which has an array of commands and all the commands get executed in all the contexts and all the output is gathered and returned for processing.

    I've included below an excerpt from an invoking script to give an example of how the data structure is built, and below that, the module itself.

    First, a couple questions.

    Has this been done before? I mean, it has to have, right? My searches haven't turned up much however. nysus seems to be working on something similar, Re: How best to validate the keys of hashref arguments?, and melezhik recently wrote about Sparrow - your own script manager, which seems to be in the neighborhood, but not quite what I'm looking for. If anybody knows of a module that already does this, I'd really appreciate it.

    How do I organize my modules? Assuming I do continue this development, I plan on rewriting contexts and commands as objects, which would by my first foray into objects with Perl, and I'm not sure how they should exist with respect to each other. In general, what are the implications between Foo::Bar and Foo::Baz as opposed to Foo::Bar and Foo::Bar::Baz? And in this case, Ops::Context and Ops::Command, where Ops::Context would use Ops::Command and a calling script would have to use both, or Ops::Command and Ops::Command::Context where Contexts are extensions of Commands and the invoking script only uses one or the other, depending on the complexity of the task?

    Finally, any feedback on the code below would be appreciatel, any smoking guns that would explain this hole in my foot, or anything I may have done clumsily for which Perl has a better construct.

    For instance, the line where I access the array of commands:

    for my $cmd (@{$ctxt->{commands}}) { ...
    Is there a better way to say that?

    An excerpt from a script that invokes the module:

    And the module:

    Thank you for taking the time to look at this.


Looking for a standalone separator for Perl/Tk
1 direct reply — Read more / Contribute
by kbrannen
on Mar 24, 2017 at 13:04
    I'm looking for a standalone separator widget for Perl/Tk, something to draw a line between other widgets. Imagine something like HTML's "hr" tag that can be horizontal or vertical ... or for those familiar with the old Motif, something like XmSeparator.

    Does anyone know of an existing widget for this? If not, what could easily be made to do this?

    I can do an empty Frame with a raised relief and a non-zero borderwidth like:
    my $frame = $parent->Frame(); my $info = $frame->Label(-text => "General Info")->pack(); # separator ... sort of $frame->Frame(-background => "black", -borderwidth => 1, -relief => 'r +aised', -height => 2) ->pack(-fill => 'x', -padx => 5, -pady => 5); my $comments = $frame->Label(-text => "next widget")->pack();
    which gets me really close, but it seems cumbersome. I assume I can do something similar for verticals with some option changes, but I haven't tried it yet. Is there a better alternative anyone can suggest?
Capture::Tiny alternative
4 direct replies — Read more / Contribute
by melezhik
on Mar 24, 2017 at 06:23

    Hi! I have been using Capture::Tiny to read from processes I launch in my scripts. It works pretty good. Good module. The only thing I need more is reading processes STDOUT "in real time" which impossible with this module as it captures all the data till the process exits and then return it. It makes user waits till long running command finishes and don't let him to see it's STDOUT in real time.

    Another solution with well known construction:

    open(my $fh, '-|', $system_command) or die $!;
    while (my $line = <$fh>) {
        # Do stuff with each $line.
    Does not work for me, as it for mysterious reasons _sometimes_ ( some rare cases of $system_command ) it waits forever even when $system_command finishes and return all the data as STDOUT.

    Any suggestions?

    PS both workaround for open(my $fh, '-|', $system_command) or suggestion new IPC related module would be fine.

Joining multiple lines together while parsing
5 direct replies — Read more / Contribute
by Arengin
on Mar 24, 2017 at 06:08

    I have the following code:
    #!/usr/bin/env perl use strict; use warnings; use Data::Dumper; #read input data: my @rows; #set record separator to 3 line feeds. local $/ = "\n\n\n"; while ( <> ) { next unless m/Dumpdata example/; #map key-values out of this 'chunk'. my %row = m/\s*(\w+)\S*\s+(\S.*)/g; push @rows, \%row; } #print whole data structure for debugging: print Dumper \@rows; #define columns and ordering for output: my @output_cols = qw /Info Detail Warning Spec/; #iterate rows foreach my $row ( @rows ) { #print fields selected from output_cols. #use a 'hash slice' - look it up in perl docs. print join ";", @{$row}{@output_cols},"\n"; }

    It works just fine except for the problem, that it ends at the line end.
    If for example Info is on 2 lines I only get the first part in the output.

    Dumpdata example ----------------- Warning bad news here Detail: Some really nice infos these are Info: This is a problem but there is a solution Spec: 2nd of 4

    The expected output for this should be:
    "bad news here"; "Some really nice infos these are"; "This is a proble +m but there is a solution"; "2nd of 4"

    Thanks you haukex for reminding me to post that too.

    My above code would return This is a problem but it should return This is a problem but there is a solution

    Any ideas on how to get this done?

    Thank you so much

Alternative to
4 direct replies — Read more / Contribute
by sectokia
on Mar 24, 2017 at 04:59

    Hi Monks, what is built in to perl dist these days that is meant to take the place of Especially for the HTTP essentials like params and header?

    Also whats with the apparent 'crusade' against Removing it from dist is fine (great even), but it seems that someone is especially out to make it hard to even get installed. I had some older code to run and I noticed that:

    • Bigger dists (think Ubuntu) got on exclusion lists, even thought they package a pre-compiled version of pretty much everything on cpan. In particular its banned as a security threat?!
    • Someone seems to have 'minified' its build scripts on cpan. Previously I believe it had a mechanism that told you gcc/make wasn't installed. Now it just throws pages of errors that would be impossible to interpret for those who don't know about gcc/make.
Using PerlPod Creatively
4 direct replies — Read more / Contribute
by samijoseph
on Mar 24, 2017 at 03:21


    I am interested to understand what this guy did, but i am unable to, can someone please break it down to a newbie

    I've spent the last several days at work, trying to "take over" some work left behind by a departing colleague. I realized we didn't have some of his bash scripting in ansible or in a repo, so I decided this would be a good opportunity to fix all of those problems. After a little while it became clear his script was a set of functions, run in a loop-within-a-loop to iterate through a bunch of things. In the middle, between these two loops, is a pile of inline *PERL* that runs as a bash function and passes data back and forth in all directions. This Perl generates some dynamic SQL commands each loop.

    I hate SQL.

    Okay... read the Perl. Now, it's been a long time and a long way since my last string of PERLs, so i didn't really grok 100% what I was reading, but I got the gist of it. Finally figured out the SQL wasn't the problem.

    Another day goes by, and I finally figure out his code is self documenting! That was what all the little bits were in the perl I didnt get. PerlPod. So now I can figure this out easy . Run it, read the code, make a change, run it... *boom* what?


    It took me several more hours and a few beer, and it finally clicked. He was using PerlPod to document out the code he didn't want to run, and commented out the documenting code to run the code he wanted. What looked commented out, wasn't, and what looked like a pile of variables being set, was just a bunch of commentary. He was using a documentation module for *flow control*.

    What a Hacker. Holy shit. Blew. My. Mind.

    I just got schooled very seriously. It's nice to know I can still improve *that much*, even from where I am.

    When PerlPod is used to document something, anything between control codes is not interpreted but treated as commented text. He would comment out the control codes (thus rendering the text interpretable) on the parts meant to run, which would differ between machines.

Get current time using Joda time format
4 direct replies — Read more / Contribute
by ravi45722
on Mar 24, 2017 at 02:38

    I need to get current time using Joda time format ( Is there any way to get that???

     Ex : "EEE MMM dd HH:mm:ss.SSS yyyy"

    Needed to convert into

     "Fri Mar 24 11:54:55.234 2017"  
parsing a terrible /etc/hosts
3 direct replies — Read more / Contribute
by f77coder
on Mar 24, 2017 at 01:15
    Hello, I'm attempting to parse this monster of a hosts file that is a most un-formatted file with ip4 and ip6 address with comments scattered everywhere. sometimes there are two columns separated by space, sometimes 3 columns, sometimes 4. #SpySweeper.Spy.Cookie

    # 1-800-hostingAS3321069.41.160.0 - 2a02:598:2::1095

    so i want to clean the old file by removing comments, and duplicates, so far i have
    my @array = (); $#array = -1; my @tmp_array = (); $#tmp_array = -1; my @uniq = (); $#uniq = -1; my $i = 0; open(HOST_ORIG,'<', $file_read ) or die "Can't open $file_read: $!"; chomp(@array = <HOST_ORIG>); foreach $i (4...scalar(@array)-1) { (my $local_127, $tmp_array[$i] )=split(" ",$array[$i]); }; close(HOST_ORIG); my %seen; my @uniq = grep {! $seen{$_}++} sort(@tmp_array); open(TEMP, '>', $file_write)|| die "\n error opening file $file_write +\n"; print TEMP "#Hosts file\n"; print TEMP "#Last Modified -> ". localtime() . "\n"; print TEMP "# \n"; print TEMP "# localhost: Needs to stay like this to work\n"; print TEMP "\t localhost\n"; print TEMP "# \n"; foreach $i (1...scalar(@uniq)-1) { print TEMP "\t $uniq[$i]\n"; } close(TEMP);

    it works except when there are 3 or more columns, the 3rd and 4rth columns get wrapped around to a new line like this


    how do i throw away the rest of the line if it exists?


Learning Perl by Doing
4 direct replies — Read more / Contribute
by raywood
on Mar 23, 2017 at 23:04

    I would like to learn Perl by working through specific cases where I need it. This is the first such case. I have a situation much like the one described in an earlier discussion (Extracting blocks of text). Specifically, I have a number of old WordStar files in plain text. Each such file contains multiple .pa-delimited documents (consisting of various numbers of lines and paragraphs of text) that should be broken out into separate files. For example, one of these WordStar files might contain something like this:

    Text text text .pa Other text text text .pa
    In that example, resulting file no. 1 would contain "Text text text," and resulting file no. 2 would contain "Other text text text."

    I assume, but am not certain, that every .pa appears at the left margin, and is followed by no other characters on the same line.

    The earlier discussion suggested this solution, where the delimiter was the word "term" rather than ".pa":

    #! perl -slw use strict; my @array = split 'term', do{ local $/; <DATA> }; shift @array; ## Discard leading null print '---', "\n", $_, "\n" for @array; __DATA__ term { yada yada 12345 () ... } term only occurs here { could be 30 lines here but never that word again until another block starts yadada } term, etc.
    My questions, from that example:

    1. That old discussion mentioned RAM concerns when slurping. My system has 16GB RAM. The files I am working on are small. But I may adapt the solution to other, larger files. When does RAM become an issue?

    2. How would I adapt this solution to refer to a separate input file? In the suggested solution, the Perl code seems to be added to the start of the text file. I would rather have a separate Perl script and specify the target file at runtime.

    3. What would be the best reference source, for purposes of interpreting the few Perl codes suggested in that solution?

    4. Which version of Perl should I install, to run this code?

    Many thanks.

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 chanting in the Monastery: (5)
    As of 2017-03-25 13:06 GMT
    Find Nodes?
      Voting Booth?
      Should Pluto Get Its Planethood Back?

      Results (311 votes). Check out past polls.