Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

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
To find and count a repeating pattern in a line
2 direct replies — Read more / Contribute
by punitpawar
on Feb 08, 2016 at 14:24
    I wanted to know if there is any way by using regular expression to count the occurrences of a repeating pattern in a line ?
    here is the problem statement
    Given a log file:
    some garbage...from:123.54,78.21...more,82,124.54...more some more garbage...from:11.54,,98.65 ... Assumption: these coordinates will always appear in sequence: from ... to... from ... to... But these from - to pair may or may not be on same line
    Write a script to return pairs of (from, to) coordinates.
    The only way I could think of was by splitting the line....But I feel there should be a better way. here is my code below
    #!/usr/bin/perl use Data::Dumper; open(FH,"<abc.txt")or die EXPR; while (<FH>) { my @words = split(/ /,$_); foreach (@words) { if ($_=~/from:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/) { print "$1- \n"; }elsif ($_ =~/to:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/){ print "$1 \n"; } } } close (FH);
    This is the sample input file abc.txt
    hshhhgljlkjglgkjj from: aegighighighilg to: iiuf +duifuiuih from: hiihhj to: hhouhoho from: igilgojhjh to:198.18.6 +6.10 igighliho from: highighioouhouhhhoh to:
    And the output I am expecting is , , , ,
Seek and Find
1 direct reply — Read more / Contribute
by hbrown.bios
on Feb 08, 2016 at 12:06
    Hey guys, I'm still pretty new to perl, so I'm not even sure is this will work, but here is what I am trying to do. I have 2 files. say file A has a list of numbers (which I can put into an array because there aren't very many of them) and I want to search file B which has 7 columns. I want perl to print the matching line to a new file if column 2 matches a value in file a (or the array) AND matches a search phrase in column 7 and if the value in column 4 falls into a specified range. Any and all help would be greatly appreciated!
Why are my hash keys undefined?
3 direct replies — Read more / Contribute
by biologistatsea
on Feb 08, 2016 at 12:03

    Below is part of a script that I think should read a file into a hash, so I can look up the record using the key from other parts of the program. The print statements include are for trying to find out what's wrong! The program finds the name successfully (based on the print in the if loop), and creates the hash with the right values, but the keys are always empty (based on the output of the while loop that prints the hash)

    open (NOV, '<', $novo); my %denovo; while (my $line = <NOV>){ chomp $line; if ($line =~ /([^,]*)$/){ my $name = "$1"; print "name is $name\n"; $denovo{$name} = "$line"; } } print "hash denovo is:\n"; while( my( $key, $value ) = each %denovo ){ print "$key: $value\n"; } close NOV;

    I've tried changing the presence of / types of commas around $name when defining each hash entry. The keys should look like following: R2b.9138.9138.2(intensity=1341005.0692)_2 so I've tried using simpler names in case there were some illegal characters or something - but nothing works! I think I must be misunderstanding something fairly fundamental. Any help would be enormously appreciated.

PDF::OCR2 results not what I was hoping for
1 direct reply — Read more / Contribute
by nysus
on Feb 08, 2016 at 10:33

    I'm trying to OCR this document.

    The results are disappointing to say the least. The output was basically just random characters with lots of blank lines. None of the text appearing in the original PDF was recognized. When I tried on a "clean" document converted straight to PDF from a word processing document, the module worked fine. So apparently OCR2 just doesn't have the logic to pull text from more sophisticated documents that are scanned.

    I know that the PDF::OCR2 just provides an interface to tesseract/imagemagick so this probably isn't the best forum for this question but I'm hoping someone can give me some advice that points me in the right direction.

    I'm interested in pulling out the time and location data from the document.

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

Tk::LabEntry - how to reach the configuration of label via callback?
2 direct replies — Read more / Contribute
by vagabonding electron
on Feb 07, 2016 at 08:28
    Hi All,

    I try to validate the content of entry in Tk::LabEntry widget. I would like to change the configuration of the label part if the content is not a number (simply to color it red). I can do this with the background of the entry (code below), however an attempt to reach the option -labelBackground produces an error message "unknown option".

    I know that Tk::LabEntry is a Mega-Widget. I cannot find a way to reach its configuration (that is, the label part) via callback. It would work if I call the widget by name (that is,  $le->configure(-labelBackground => 'red'); would do the job in the code below). I would like to stick with callback however since I have several such widgets in the real application.

    Please give me an advice. Thank you!

    #!/perl use strict; use warnings FATAL => qw(all); use Tk; use Tk::LabEntry; use List::Util qw(first); use Scalar::Util qw(looks_like_number); my $mw = MainWindow->new(); $mw->title("Test"); my $test = 8; my $width = 250; my $length = 125; $mw->minsize($width, $length); my $FONT = $mw->fontCreate(-family => 'verdana', -size => 14, -weight => 'normal'); my $le = $mw->LabEntry(-label => 'Value', -labelPack => [qw/-side left -anchor w/], -labelFont => '9x15bold', -font => $FONT, -relief => 'ridge', -textvariable => \$test, -width => 2, )->pack(); $le->bind('<Key>' => sub { labelCheck($_[0]);}); MainLoop; sub labelCheck { my $x = $_[0]->get(); if ( !(looks_like_number($x)) or ($x < 0) ) { $_[0]->delete(0, 'end'); $_[0]->configure( -background => 'red'); # $_[0]->configure( -labelBackground => 'red'); } else { $_[0]->configure( -background => '#f0f0f0',); # $_[0]->configure( -labelBackground => '#f0f0f0'); do_something(); } return 1; } sub do_something { print $test, $/; }
what is this error means Use of uninitialized value $. in concatenation (.) or string
2 direct replies — Read more / Contribute
by aca
on Feb 07, 2016 at 04:35
    Hi i am new to Perl programming. I am writing the HTML and jquery in the code. I am not able to figure out why the HTML part is not working. Here is the code:
    #!/usr/bin/perl use warnings; use strict; use CGI; use CGI::Carp qw(fatalsToBrowser); my $cgi = CGI->new; #print $cgi->redirect(-location=>'test1.cgi'); print $cgi->header( -type=> "text/html" ); print <<EOF; <!DOCTYPE html> <html> <script src=" +y.min.js"></script> <script> var embeddedVideo = { requestVID : function() { $.ajax({ url:"serve.cgi", success: function () { alert("done"); }, }).fail(function( jqXHR, textStatus, errorThrown ) { console.l +og(textStatus,errorThrown)}); }, }; $(document).ready(function(){ embeddedVideo.requestVID(); }); </script> </head> </html> EOF
    In the log it is writing like
    Use of uninitialized value $. in concatenation (.) or string at /usr/ +lib/cgi-bin/test.cgi line 13.
    Please tell me where it is going wrong.I don't get any useful information relating to this.And i am not sure how to make it working. Any help will be appreciated.Thanks in advance
mro's which to use for flexibility?
1 direct reply — Read more / Contribute
by perl-diddler
on Feb 07, 2016 at 02:51

    I have a call-graph that doesn't seem to work with the standard or 'c3' mro's:

    <main>____ / \ \ <CP> <SW> <V(main)> \ \ <V(CP)> <V(SW)> Note: 'V(x) != V(y)'

    Different error messages for the default and c3 mro's:

    mro:c3: Inconsistent hierarchy during C3 merge of class 'SW': current merge results [ SW, ] merging failed on 'D' at src line. main::BEGIN() called at src line eval {...} called at src line BEGIN failed--compilation aborted at src line. Inconsistent hierarchy during C3 merge of class 'SW': current merge results [ SW, ] merging failed on 'D' at src line during global destruction. mro:default: main::ISA=["CP", "SW", "D"] Can't locate object method "cp_new" via package "D" at src line. at src line.

    Also tried adding CP onto 'end' of @ISA, as the ClientProc has the "cp_new" method I need, but that didn't work either.

    Is there a mro that supports (or can be configured to support) a D-module being called multiple times in the hierarchy. Of note: the calls creating 'D', pass different args to "new", that define different subs-by-name in the caller.

    In some way, it's like a call to exporter -- with the EXPORTS list (et al.) being a parameter list of subs to export to future users of the original module.

    Solutions to make the above work would be very welcome.

Aliasing Module->method
2 direct replies — Read more / Contribute
by gerases
on Feb 06, 2016 at 13:54
    Hi, It seems that Time::Piece module doesn't export strptime. So the only way to use it is to do:
    Which is too long. Can I alias some "x" to Time::Piece->strptime? I tried the things offered here: but that doesn't seem to work. Thanks for any ideas!
Why is perl -MO=Deparse -f obf.txt unsafe?
2 direct replies — Read more / Contribute
by vpelss
on Feb 06, 2016 at 11:52

    It is my understanding, that perl -MO=Deparse does not actually run the PERL code. Is that correct?

    If so, then why is the following run on a website able to be attacked?

    open (TXTFILE , ">obf.txt"); print TXTFILE $string; close(TXTFILE); #deparse $string = `perl -MO=Deparse -f obf.txt`;

    I thought I read somewhere that "eval" (or was it an other PERL command?) actually ran the code during PERL's compiling phase, and therefore before the rest of the PERL code ran. Is that accurate? If so, maybe that is why it is unsafe.

    I have tried many different attempts to attack that code on my home environment but with no success. So obviously the interent is safe from the likes of me.

    For all the angry Perl Monks out there don't jump all over me because my previous searches on this topic came up empty ;)
Exit codes and signals
3 direct replies — Read more / Contribute
by Anonymous Monk
on Feb 06, 2016 at 08:37
    Dear Monks, I have a process that forks into a parent that runs a monitor and a child that again runs another grandchild process. The grandchild process can terminate with 0 or non-zero exit code, which I can receive in the forked process, and return to the parent. But if the grandchild terminated due to a TERM signal, the exit code seen by the parent monitor is zero.
    elsif ($pid == 0) { # .... my $exitstatus = ... my $returnvalue = $exitstatus >> 8; my $signalled = ($exitstatus & 127); print "status=$exitstatus, signal=$signalled\n"; return($returnvalue); }
    In the above, I would like to return the full $exitstatus so the monitor can know the reason the grandchild quit. One possibility, although I am unsure how unconventional, is to return ($returnvalue | $signalled). Any help is greatly appreciated.

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 the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others musing on the Monastery: (9)
    As of 2016-02-08 21:52 GMT
    Find Nodes?
      Voting Booth?

      How many photographs, souvenirs, artworks, trophies or other decorative objects are displayed in your home?

      Results (286 votes), past polls