Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

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
How to use AnyEvent::Handle to read data from a websocket?
1 direct reply — Read more / Contribute
by pudda
on Sep 29, 2020 at 08:41


    I'm new with perl, so please have patience if I misunderstood anything, or got something wrong.

    What I'm trying to do is connect to a websocket, read the data the ws is sending and do some stuff with it. My code is connecting to the ws but when I try to read and print in the console the data readed it shows nothing. Can you guys help me?

    here's my code:

    #!/usr/bin/env perl use strict; use warnings; use lib 'lib'; use Data::Dumper; use AnyEvent; use AnyEvent::Socket; use AnyEvent::Handle; $|++; my $cv = AnyEvent->condvar; my $ws_handle; $ws_handle = AnyEvent::Handle->new( connect => [ 'localhost', '8082' ], keepalive => 1, on_eof => sub { print ("! Server disconnected"); }, on_read => sub { my ($handle) = @_; my $buf = delete $handle->{rbuf}; print "teste"; }, on_connect => sub { my ($handle, $host, $port, $retry) = @_; print "Server connected\n"; # this works }, on_connect_error => sub { my ($handle, $message) = @_; print $message; }, ); $cv->recv;
Question about regex.
6 direct replies — Read more / Contribute
by that_perl_guy
on Sep 28, 2020 at 22:10

    Hi Monks,

    I will be extremely thankful if the monks here could help me understanding regex in Perl.

    Suppose I have a text file that has these lines:

    This is line one. Line Two is this. Third line starts here. This is line four. This is line five. This is line six. This is the seventh line. This is line eight.

    If the record contains the word "third" our "four", I want it to print the whole record, meaning the stuff between the empty lines, not just lines with those words in it. But I am not able to write it correctly. Here is what I have tried:

    use strict; use warnings; open my $fh, "+<", "testlines.txt"; while (<$fh>) { if ($_=~ /(third | four)/si) { chomp; local $/ = "\n\n"; print "line is: $_\n"; } }

    And it prints:

    >perl line is: Third line starts here. line is: This is line four.

    But what I want is:

    This is line one. Line Two is this. Third line starts here. This is line four

    Where am I going wrong? Please guide. Please note, this is just an example. Depending on the data supplied the other lines in the file may contain some different words.

    Not sure if this matters, but I'm on Windows 10 with Strawberry Perl version 5.32.

DBIx::Class : match integer-cols having specific bits set
1 direct reply — Read more / Contribute
by bliako
on Sep 28, 2020 at 14:26

    Enlightened Brothers,

    I am having bit (!) trouble with telling DBIx::Class to match records where a specific column of integer type (actually BIGINT) has specific bit(s) set. The equivalent SQL is something like: select * from TABLE where (roles & 4) = 1 (Edit: the RHS of this where expression, i.e.: =1 was written rather hastily and it does not make sense for checking if the 2nd LSbit is set. roles=4 is much clearer and probably faster. Instead,  (roles&4) = 4, (roles&4) > 0. (roles&4)=0 make more sense in my particular scenario)

    Since we are on the topic, I have not yet understood how to use the column-name in a search with DBIx::Class. For example how to DBIx::Class this: select * from TABLE where (roles & 4) = (roles & 2) ?

    I can also settle for someone telling me how to pass a custom WHERE-in-SQL using DBIx::Class::ResultSet::search(), if possible.

    Oh! MySQL latest

    bw, bliako

substrings that consist of repeating characters
13 direct replies — Read more / Contribute
by Anonymous Monk
on Sep 27, 2020 at 13:30

    Hi. I am studying regular expressions and wanted to write a script that searches a DNA string for the longest substrings that consist of repeating letters. For example: CCCCC or GGG or AAAA etc. I managed to do that, but i am not very happy with the end resuslt. I was hoping to get most of the work done with a regex, in that regard i have failed. Furthermore there are statements in the while loop that look doubtful, and the idea of using an array to store the substring along with its length might not be good. Any advice is welcome. Thank you.

    use strict; use warnings; my $string = "AAATTTAGTTCTTAAGGCTGACATCGGTTTACGTCAGCGTTACCCCCCAAGTTATT +GGGGACTTT"; my @substrings; while($string =~ /([ACTG])(\1+)/g){ my $comb = $1.$2; my $len = length($1) + length($2); push @substrings, [$comb,$len]; } my @sorted = sort {$b->[1] <=> $a->[1]} @substrings; foreach my $substring (@sorted){ foreach my $element (@$substring){ print "$element "; } print "\n"; }
Hyperlink Question
1 direct reply — Read more / Contribute
by Anonymous Monk
on Sep 26, 2020 at 22:21

    Hello Monks, I am somewhat new to Perl but am trying to learn it because I have seen several examples over the years of what this language is capable of, it is very powerful in the right hands. I am trying to use Win32::OLE and am working with an example I found on your website so the code may look somewhat familiar. All I am doing is creating a word document, writing and formatting 3 lines, then writing a hyperlink, then writing the 3 lines again. For some reason, the calculation of the range object AFTER the hyperlink is formatted is not calculated correctly even though it is exactly the same code that I used BEFORE formatting the hyperlink (that worked correctly). Can you please enlighten me as to what I am missing? Thank you in advance!

    #!/usr/bin/perl use strict; use warnings; use Win32::OLE; my $word = Win32::OLE->new('Word.Application') or die $!; $word->{'Visible'} = 1; # Create new document my $d = $word->Documents->Add; # define selection my $s = $word->Selection; my @lines = ( "This is test line 1", "This is test line 2", "This is test line 3", ); # $c is the color # $start is the start of Range # $end is the end of Range # $r is the Range object my ($c, $start, $end, $r) = (2, 0, 0, ); # Write out the @lines for my $line (@lines) { $start = ($d->Characters->Count)-1; $end = length($line)+ $start; $s->TypeText($line); # define the Range $r = $d->Range($start, $end); # Set font properties $r->Font->{Size} = 18; $r->Font->{ColorIndex} = $c++; $r->Font->{Name} = 'Courier New'; $s->TypeText("\n"); } # Now insert a hyperlink my $line = 'hyperlink'; $start = ($d->Characters->Count)-1; $end = length($line) + $start; $s->TypeText($line); # define the Range $r = $d->Range($start, $end); # Set font properties $r->Font->{Size} = 12; $r->Font->{Name} = 'Arial'; $r->Font->{Bold} = 1; $d->Hyperlinks->Add({Anchor => $r, Address => ""}); $s->TypeText("\n"); # Now write out the @lines again for my $line (@lines) { $start = ($d->Characters->Count)-1; $end = length($line)+ $start; $s->TypeText($line); # define the Range $r = $d->Range($start, $end); # Set font properties $r->Font->{Size} = 18; $r->Font->{ColorIndex} = $c++; $r->Font->{Name} = 'Courier New'; $s->TypeText("\n"); } $word->WordBasic->FileSaveAs("c:\\test.doc"); # house keeping, clean up our instances $d->Close(); $word->Quit(); undef $word;
WWW::Mechanize::Chrome Can't Connect without knowing the port?!
1 direct reply — Read more / Contribute
by dexmar
on Sep 26, 2020 at 16:15

    Hello Monks!

    I have a Centos 8 VM running on my local machine with a fresh install of Chrome 87.0.4270.0 and WWW::Mechanize::Chrome installed to version 0.60. In trying the sample project I get this error:

    Can't connect without knowing the port?! 0 at /usr/local/share/perl5/C +hrome/ line 316.

    I tried setting the port as per the docs:

    my $mech = WWW::Mechanize::Chrome->new(port => 9222);
    Same error. I followed this earlier post as well but no luck:

    From the $TRACE it appears the port is not being set:

    2020/09/26 13:02:28 Spawning $VAR1 = [ '/usr/bin/google-chrome', '--remote-debugging-port=0', '--enable-automation', '--no-first-run', '--mute-audio', '--no-zygote', '--no-sandbox', '--safebrowsing-disable-auto-update', '--disable-background-networking', '--disable-breakpad', '--disable-client-side-phishing-detection', '--disable-component-update', '--disable-hang-monitor', '--disable-prompt-on-repost', '--disable-sync', '--disable-translate', '--disable-web-resources', '--disable-default-apps', '--disable-infobars', '--disable-popup-blocking', '--disable-gpu', '--disable-save-password-bubble', 'about:blank' ]; 2020/09/26 13:02:28 Spawned child as 7191 Can't connect without knowing the port?! 0 at /usr/local/share/perl5/C +hrome/ line 316.
    Any thoughts on this would be much appreciated!! Thanks! Ed
Net::OpenSSH reconnect master if conn. closed
2 direct replies — Read more / Contribute
by Bolemo
on Sep 26, 2020 at 12:41

    I have another question regarding Net::OpenSSH

    I am currently creating one master connexion to a device when my script is started, and then I only regularly send commands on that device using open3.

    It works really great, but I encounter one problem : if the remote device is restarted, then the master SSH connection is disconnected (obviously), but is never reopened, meaning the Net::OpenSSH does not try to reconnect a closed/lost master connection when an open3 command is called.

    How can implement the master connection to be recreated when it is lost?

    Thank you!
tr operator in eval -- updated
8 direct replies — Read more / Contribute
by pgmer6809
on Sep 25, 2020 at 22:55

    Using Perl 5.26.1 under Linux I want to use a variable in the searchlist of a tr operator expression. The example on p.76 of the camel book, has two things wrong with it

    a) eval " ... code ... " as shown in the book gives an eval error message. To get rid of the message I need to put the code in braces.

    b) even putting the code in braces it does not work. See this:

    $kards = -99; $bad="AKQJT98765432KKKK"; $card='K'; eval {print "eval is testing for $card in $bad \n"; $kards = $bad =~ tr/$card//; # tried also tr/$card/$card/; +same bad result. }; print "Num of $card in $bad = $kards \n"; $king = $bad =~ tr/K//; print "Num of K in $bad is = $king \n"; =cut Returns the following: eval is testing for K in AKQJT98765432KKKK Num of K in AKQJT98765432KKKK = 0 Num of K in AKQJT98765432KKKK is = 5 =end

    Why isn't the variable $kards set to 5 as it should be?


    The problem is that $kards should be set to the result of the eval execution, not put inside the eval execution. So this works:

    $kards = -99; $bad="AKQJT98765432KKKK"; $card='K'; # this next bit works. xtr is just so I can print what eval is eva +l ing. $xtr = "$bad =~ tr/$card//;" ; $kards = eval "$bad =~ tr/$card//;"; #<====== Note the ; " ; at + the end. This seems required. print "xtr kards = $kards from eval cmd : $xtr\n"; #output: xtr kards = 5 from eval cmd : AKQJT98765432KKKK =~ tr/K// +;

    but note that the code eval runs must be in double quotes, not in braces. so <code>$kards = eval {$xtr;} ; does NOT work.

Visualize Perl Program
3 direct replies — Read more / Contribute
by aartist
on Sep 25, 2020 at 15:07
    How I can visualize a Perl program? For example I like to see all the perl variables and the line-numbers or subroutines where it is used. I understand that variables can be created on the fly with eval and $$ and even another name-space but let's ignore for them for now, as my current code base doesn't have that.

mod_perl and CGI behavior
4 direct replies — Read more / Contribute
by naChoZ
on Sep 25, 2020 at 13:52

    crossposted at stackoverflow here.

    This has got to be something silly I'm doing wrong. It's such a newbie type problem.

    The original script is something that sits and waits for a 3rd party to connect and POST some xml to it, it takes that xml, does some validation, and stores it in a db. That part is fine. The problem is my response. I'm trying to use the header() function from CGI and it's just not behaving. It comes up blank. Obviously I could just do this manually and just print the header string, but now I'm really curious why this is behaving so strangely.

    Here is a stripped down test version of the cgi script:

    #!/perl/bin/perl use strict; use warnings; use Data::Dumper::Names; use CGI qw(:standard); use Apache2::Connection (); use Apache2::RequestRec (); $| = 1; # Grab the request object provided by mod_perl. # our $request_obj = shift; our $connection = $request_obj->connection; our $remote_ip = $connection->client_ip(); my $cgi = CGI->new($request_obj->args()); print STDERR Dumper($cgi); my $input = $cgi->param('POSTDATA'); print STDERR Dumper($input); my $cgi_header = $cgi->header(); print STDERR Dumper($cgi_header); #my $cgi_full_header = $cgi->header(-type => 'application/xml', -statu +s => '400 Bad Request' ); my $cgi_full_header = $cgi->header(-type => 'application/xml'); print STDERR Dumper($cgi_full_header); my $q = CGI->new({}); print STDERR Dumper($q); my $q_header = $q->header(); print STDERR Dumper($q_header); #my $q_full_header = $q->header(-type => 'application/xml', -status => + '400 Bad Request' ); my $q_full_header = $q->header(-type => 'application/xml' ); print STDERR Dumper($q_full_header); exit;

    And the output:

    $cgi = bless( { '.r' => bless( do{\(my $o = '94118860562256')}, 'Apach +e2::RequestRec' ), 'param' => { 'POSTDATA' => [ 'test' ], 'XForms:Model' => [ 'test' ] }, 'use_tempfile' => 1, '.fieldnames' => {}, '.charset' => 'ISO-8859-1', 'escape' => 1, '.parameters' => [ 'XForms:Model', 'POSTDATA' ] }, 'CGI' ); $input = 'test'; $cgi_header = ''; $cgi_full_header = ''; $q = bless( { '.parameters' => [ 'XForms:Model', 'POSTDATA' ], 'escape' => 1, '.fieldnames' => {}, '.charset' => 'ISO-8859-1', 'use_tempfile' => 1, '.r' => bless( do{\(my $o = '94118860562256')}, 'Apache2 +::RequestRec' ), 'param' => { 'POSTDATA' => [ '' ], 'XForms:Model' => [ '' ] } }, 'CGI' ); $q_header = ''; $q_full_header = '';

    And here is the simple test script I'm using to send the POST.

    #!/perl/bin/perl use strict; use warnings; use DBI; use URI; use LWP::UserAgent; use Data::Dumper::Names; my $ua = LWP::UserAgent->new; $ua->max_size( 131072 ); $ua->agent('test_xml_pusher'); $ua->ssl_opts(verify_hostname => 0); my $url = URI->new; $url->scheme('https'); $url->host('xxxxxxxxxxxxxxxxxxxxxxxxx'); $url->port(443); $url->path_segments('test.cgi'); # Yes, I know... it's not valid xml... don't care for the purposes o +f this test. # my $xml = 'test'; my $response = $ua->post( $url, Content => $xml, 'Content-Type' => 'ap +plication/xml' ); print Dumper($response); my $status_line = $response->status_line; print Dumper($status_line); my $content = $response->content; print Dumper($content);

    So why is $cgi_header empty? And why does $q end up being a reference to the same thing as $cgi even though I tried initializing it as my $q = CGI->new({});? (I also tried empty quotes instead of empty brackets.)

    Any thoughts?


    My environment is a centos 7 server running apache httpd 2.4.34 with mod_perl 2.0.11 and perl 5.22.4. (httpd is installed from from SCL, but perl and mod_perl are installed from source.)


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: (5)
    As of 2020-09-30 00:09 GMT
    Find Nodes?
      Voting Booth?
      If at first I donít succeed, I Ö

      Results (155 votes). Check out past polls.