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
Accessing passwords in a script
2 direct replies — Read more / Contribute
by nysus
on Mar 25, 2017 at 16:12

    I have a script that needs passwords for things like mysql databases on other servers. I want to do this as painlessly and as securely as possible. So what I'm thinking is that my script would prompt for a single master password and then it would be granted access to the other passwords. I found this possible solution which explains how to use the KeePass module which seems like it might be a good route. But I wanted to get some input from the Monks who might have other good ideas. Many thanks.

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

Need clean code
3 direct replies — Read more / Contribute
by ravi45722
on Mar 25, 2017 at 13:34

    I am learning the Perl code. I also want to use the beauty of the perl.

    I can write like this

     $var or $var = 30;

    But in this case how can I write the code using or

    Or is there any smart way to write this

    if (undef $var) { $x = 40; } else { $x = 50; }
Using an element in a Hash of Arrays to access the key
5 direct replies — Read more / Contribute
by orangepeel1
on Mar 25, 2017 at 13:08
    I have a hash of arrays like this:
    my @array1 = ("one", "two", "three", "four", "five"); my @array2 = ("banana", "pear", "apple"); my %hash = ( numbers => \@array1, fruit => \@array2 );
    I would like to use an element of the array to access the key. So for example, if I have "banana", I would like to print "fruit". However when I do  print $hash{banana} I get "use of unitialized value in print". How do I properly access this?
curl http post
1 direct reply — Read more / Contribute
by bigup401
on Mar 25, 2017 at 12:10

    anyone can help me with this. am getting this error you need a request object, not a http::response. am new to curl post

    this is the curl script

    curl https://site.com/api/inforequests -H "Authorization: Token xert34 +5llkd736gdy3" \ -d name=+80000000001 \ -d country=BXC \ -d email=3000
    #!/usr/bin/perl use LWP::UserAgent; my $ua = LWP::UserAgent->new; $ua->agent("MyApp/0.1"); $url = "https://site.com/api/inforequests"; my @headers = ("Authorization: Token xert345llkd736gdy3"); foreach my $ml(@headers) { $auth = $ml; } my $data = { name => 'john', country=> 'ca', email=> 'john@email.com', }; my $req = HTTP::Request->new(POST => '$url', 'Content-type' => 'application/json', 'Authorization' => "$auth" ); $req->content_type('application/json'); $req->content($data); my $res = $ua->request($req); if ($res->is_success) { print $res->content; } else { print $res->status_line, "n"; }
How to code a complex AoH?
3 direct replies — Read more / Contribute
by iatros
on Mar 25, 2017 at 10:43

    Here is a task that's puzzling me for quite a while now: Regularly, we get exam results of our students as a .csv file. The header has some meta data such as ID, gender, date of birth, status, exam room, seat number, exam version, etc. The following lines start with these data and the scores for 60 questions (0.0 0.5 1.0 points if the answer is wrong, half-correct, or correct). There are 6 versions (A - F) of the exam differing only by the order of the 60 questions. The information is stored for statistical evaluation which requires the correct alignment according to the exam master (a .txt file with 7 columns for version A-F and the correct answer in the 7th column).

    I tried to accommodate the .csv file as an array of hashes to generate a different .csv or tabbed .txt file in which all exam results appear in a unified order for later statistical evaluation. But something went wrong.

    Example:

    header --

    ID,gender,birthdate,order,room,seat,version,points,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

    277710814533,f,01/02/1993,m,sr_3,A11,A, 1,1,1,1,0,1,1,1,.5,1,1,1,0,1,.5,1,1,1,0,1,.5,1,1,0,1,1,1,1,1,1,1,0,0,1,0,1,.5,1,1,1,1,.5,0,1,1,1,0,1,1,1,1,1,0,1,1,1,.5,1,1,1

    755310765962,f,31/07/1992 00:00,v,aula,C11,C,1,.5,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,.5,1,0,.5,1,0,1,.5,0,.5,0,1,0,0,.5,1,1,0,.5,1,1,.5,.5,1,.5,.5,1,1,1,.5,.5

    394610513538,m,20/10/1992 00:00,m,sr_3,E13,E,1,1,0,.5,1,1,1,1,1,1,1,.5,1,1,.5,.5,1,1,1,.5,.5,1,1,1,1,0,0,.5,1,1,.5,.5,.5,.5,0,1,0,.5,0,0,1,0,1,.5,0,1,0,0,.5,1,0,1,1,0,.5,.5,.5,.5,.5,.5

    The code generates anonymous hash keys according to the following scheme:

    while ( <FH> ) { chomp ; if ( /^\d\d\d/) { ( $id , $gender , $birthday , $status , $room , $seat , $versi +on , @points ) = split ( /,/ , $_ ) ; $student = { 'id' => $id , 'gender' => $gender , 'birthday' => $birthday , 'position' => $position , 'room' => $room , 'seat' => $seat , 'version' => $version , 'points' => @points } ; push ( @candidates , $student ) ; } } ; close FH ; print "Number of candidates processed: " . ( $#candidates + 1 ) . +"\n" ;

    The compiler throws a warning for each record, e.g. "Odd number of elements in anonymous hash at /Documents//testAoH.pl line 38, line 16." but the script is executed.

    The script prints the correct number of processed records, but when I try to retrieve a specific record I only get the scalar values and the @points array yields only one (the first?) result as if it were destroyed. A data dumper output further shows that something must be internally wrong with this code.

    Data Dumper e.g.

    755310765962 $VAR1 = \{ '0' => '0', 'gender' => 'f', 'id' => '755310765962', 'points' => '1', 'room' => 'aula', '.5' => undef, '1' => '.5', 'birthday' => '31/07/1992', 'seat' => 'A11', 'version' => 'A', 'status' => 'v' };


    Any clues?


    Thx - Harald -

[OT] Mathematical photographers that program (Perl)? (Updated.)
2 direct replies — 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.

    Update 3: This is an image I've taken myself as there is some speculation the one above may be GC.

    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.


    Thanks,
    cbeckley

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
5 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.


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

    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

    <Update>
    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.
    </Update>

    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

    Arengin

Add your question
Title:
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.