Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

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
Setting Timeout in Image::Grab??
1 direct reply — Read more / Contribute
by dazz
on Mar 26, 2017 at 15:35

    I am using Image::Grab to gr1ab images off an IP Camera. That is all working OK.

    The problem I have is that the timeout for a bad connection is 3minutes but I expect to be grabbing images every 60 seconds. If there is a problem with the camera, I will end up with multiple threads running waiting for an image. I have looked at the documentation here

    I need to change the value of Timeout.

    My code looks like this:

    #get the latest image from the IP camera my $snapshot = new Image::Grab; $snapshot->timeout(5); #sets the timeout (sec) for image::grab (defau +lt is 180s) $snapshot->url("$Camera{$key}"); # create the grab object $snapshot->grab; # grab the image open (IMAGE, ">$lastsnap{$key}") || die syslog(LOG_ERR, "Couldn't ope +n file, $!"); # opens and clears th$ binmode IMAGE; # for MSDOS derivations. print IMAGE $snapshot->image; # save the image to the /var/images/Tra +ckcam folder close IMAGE or die $!;
    Perl debugger spits out the following error message:
    Can't access `timeout' field in class Image::Grab at +line 79. at /usr/local/share/perl/5.18.2/Image/ line 81. Image::Grab::AUTOLOAD('Image::Grab=HASH(0x8698344)', 5) called + at line 79

    My question is how do I change the Timeout property to 5sec?

Joining elements of an array in a hash
4 direct replies — Read more / Contribute
by orangepeel1
on Mar 26, 2017 at 13:29
    I have a hash of arrays
    @array1 = ("one", "two", "three", "four", "five"); @array2 = ("banana", "pear", "apple"); my %hash = (numbers => \@array1, fruit => \@array2 );
    I would like to go through all the keys to the hash and join the elements of each array. I have tried something like this
    foreach my $group (keys %hash) { push @group, @{ $hash {$group}}; foreach (@group) { $statement = join ",", @group; } }
    However it does not join them. Does anyone have any suggestions for how I might go about this?
Log::Log4perl help in rotating file
2 direct replies — Read more / Contribute
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
4 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 -

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 not a whimper to be heard...

    How do I use this? | Other CB clients
    Other Users?
    Others contemplating the Monastery: (3)
    As of 2017-03-27 00:57 GMT
    Find Nodes?
      Voting Booth?
      Should Pluto Get Its Planethood Back?

      Results (315 votes). Check out past polls.