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
Log::Log4perl help in rotating file
No replies — Read more | Post response
by ravi45722
on Mar 26, 2017 at 02:56
    log4perl.rootLogger=DEBUG, LOGFILE log4perl.appender.LOGFILE=Log::Log4perl::Appender::File log4perl.appender.LOGFILE.filename=/home/GEMS/ravi/Node/logs/Script.lo +g log4perl.appender.LOGFILE.mode=append log4perl.appender.LOGFILE.layout=PatternLayout log4perl.appender.LOGFILE.layout.ConversionPattern=%d : %r : %c - %m%n +

    This is my config for the logger

    I seen


    to rotate the file. I need to rotate the file based on the date. (Every day one single file). But how to add this to my conf??

    In my conf pattern %d prints 2017/03/26 12:17:33 can I change this pattern to 2017-03-26 12:17:33.432

Need regexp to pick off second parenthetical item
2 direct replies — Read more / Contribute
by cormanaz
on Mar 25, 2017 at 20:50
    Good day Bros. I am processing email sender fields, some of which have an email address embedded in a set of parentheses following a string inside another set of parentheses. I need a regexp that will get only the former, leaving the latter with the sender name. To be clear, in the following example:
    #!/usr/bin/perl -w use strict; my $sentto = 'Fred Flintstone (US) ('; $sentto =~ m/\(.+?@.+?\)/; print "First: $`\nSecond: $&"
    I would like $` to contain "Fred Flintstone (US) " and $& to contain "(". The regexp I have in there puts " (US) " at the beginning of $&. I understand why this happens, but not how to fix it. I thought about maybe a look-back assertion for a close-paren, but I have some addresses like "Barney Rubble (" so I don't think that will work. I'd like to have a regexp that will pick off the parenthetical address for both kinds of senders. Can someone suggest a solution?
    "I think computers have complicated lives very bigly. The whole age of, you know, computer has made it where nobody knows exactly what's going on." --D. Trump
How to output file data from files in an array to one singular file?
2 direct replies — Read more / Contribute
by perlnovice1900
on Mar 25, 2017 at 19:49

    Hello kind Monks, I am having difficulty pulling data from inside multiple log files and sorting that data into one singular file that consists of every file.

    I have created a perl script that can take all of the files in any directory and put the ones that are wanted into an array, (in this case I want all of the log files that start with 'secure'). I can get the files into the array no problem, but I do not know how to condense all of the data into a singular file afterwards.

    Here is my code:

    my @JanFiles; my $file; my $infile; my $JanFiles; my @files; my $dh; my @secures; my $outfile = 'secure.200601'; my $INFILE = @secures; opendir( $dh, "." ) or die "Can't open '.':$!\n"; while( $file = readdir($dh) ) { # add it to the set of files... push( @files, $file ); #print "[$file]\n"; } closedir( $dh ); # verify that @files got stuff .. print "===========================\n"; print "Verifying all file names.\n"; foreach( @files ) { print "[$_]\n"; } # Let's make a private reserve # of files that contain the word # 'secure' in file name #@secures; foreach( @files ) { if (/secure/) { if ( $_ ne "secure.200601") { push( @secures, $_ ); } } } #@secures = sort @secures; print "===========================\n"; print "Verifying only 'secure' file names.\n"; foreach( @secures ) { print "secure file = [$_]\n" } foreach( @secures ) { push (@secures, grep(/^Jan/ , @JanFiles )); } foreach( @JanFiles ) { print "JAN FILES = [$_]\n" } open (FILE, ">> $outfile") || die "Unable to open Write File! \n"; print FILE @JanFiles; close FILE; #foreach( @JanFiles ) { # print "JanFile = [$_]\n" #} exit;

    Thank you in advance. I will be here for any further needed information.

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 -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 = ""; my @headers = ("Authorization: Token xert345llkd736gdy3"); foreach my $ml(@headers) { $auth = $ml; } my $data = { name => 'john', country=> 'ca', email=> '', }; 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.


    header --


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


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 contemplating the Monastery: (5)
    As of 2017-03-26 08:37 GMT
    Find Nodes?
      Voting Booth?
      Should Pluto Get Its Planethood Back?

      Results (313 votes). Check out past polls.