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

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
LWP::Useragent - File Upload
1 direct reply — Read more / Contribute
by leefp
on Dec 14, 2018 at 16:26
    I'm trying to upload a file, via REST. but I keep getting a 500 Not a SCALAR reference I'm read numerous articles as to why...I can only speculate that my data/content is not correctly formatted.
    use strict; use warnings; use diagnostics; use IO::Socket::SSL qw( SSL_VERIFY_NONE ); use LWP::UserAgent; use Data::Dumper; use MIME::Base64; use JSON; my $json = JSON->new; my $ua = LWP::UserAgent->new(); $ua->ssl_opts( SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE +, SSL_hostname => '', verify_hostname => 0 ); $ua->default_header('Content-Type' => 'application/json' ); $ua->default_header('Content_Type' => 'form-data;boundary=xYzZY'); $ua->default_header('Authorization', "Basic " . encode_base64("adm +in:password")); $ua->timeout(600); my $file = ["/tmp/test_image.tgz.bin"]; my $url = "https://10.248.179.31/api/rest/software_package"; my $header = ['Content-Type' => 'form-data;boundary=xYzZY']; my $request = HTTP::Request->new("POST", "$url", $header, $file); # my $request = HTTP::Request->new("GET", "${url}?select=*", undef) +; print Dumper $request; my $res = $ua->request($request); if($res->is_success) { my $data = $json->decode($res->decoded_content); print Dumper $data; } else { print Dumper $res; }
    Here is what the request looks like...
    $VAR1 = bless( { '_headers' => bless( { 'content-type' => 'form-data;b +oundary=xYzZY' }, 'HTTP::Headers' ), '_uri' => bless( do{\(my $o = 'https://10.248.179.31/ +api/rest/software_package')}, 'URI::https' ), '_content' => [ '/tmp/test_image.tgz.bin' ], '_method' => 'POST' }, 'HTTP::Request' );
    And here is the response
    $VAR1 = bless( { '_headers' => bless( { 'content-type' => 'text/plain' +, 'client-warning' => 'Internal +response', '::std_case' => { 'client-date +' => 'Client-Date', 'client-warn +ing' => 'Client-Warning' }, 'client-date' => 'Fri, 14 Dec +2018 21:18:16 GMT' }, 'HTTP::Headers' ), '_rc' => 500, '_request' => bless( { '_headers' => bless( { 'author +ization' => 'Basic YWRtaW46UGFzc3dvcmQxMjMh ', '::std_ +case' => { + 'if-ssl-cert-subject' => 'If-SSL-Cert-Subject' + }, 'conten +t-type' => 'form-data;boundary=xYzZY', 'user-a +gent' => 'libwww-perl/6.26' }, 'HTTP: +:Headers' ), '_uri' => bless( do{\(my $o = +'https://10.248.179.31/api/rest/software_package')}, 'URI::https' ), '_content' => [ '/tmp/test_ima +ge.tgz.bin' ], '_method' => 'POST' }, 'HTTP::Request' ), '_content' => 'Not a SCALAR reference at /usr/lib/per +l5/vendor_perl/5.18.2/LWP/Protocol/http.pm line 256. ', '_msg' => 'Not a SCALAR reference' }, 'HTTP::Response' );
Print text on the same line after match
4 direct replies — Read more / Contribute
by periodicalcoder
on Dec 14, 2018 at 15:16
    Hello all, it has been a while for me. You were all a huge help with my last project.

    This is actually a follow-up of that same project, and while I feel that this should be simple I cannot find (or don't know enough to adapt) a solution online. I have a text file with a line (there will only ever be a single line that matches) like this:

    N1*PE*COMPANY NAME INC*XX*123456~

    **edit: on Windows using Strawberry Perl with a .pl script** I need to extract the number at the end of this line, excluding the tilde, and add it to a variable so that $number = 123456. So far I have only been able to come up with the match regex, but I'm not sure how to get the text at the end. So far I have this which gives the entire line:

    perl -ne "print if /INC\*XX\*/" cr835.txt

    Inside my perl script I assume that I will use something like this, but of course including any recommended code changes:

    my $number = "perl -ne "print if /INC\*XX\*/" cr835.txt";

    My end goal is to detect this number and use it to rename the file. I already have the code tested for renaming the file with a timestamp and I just need help populating this variable.

    Thanks a bunch!

    peridicalcoder

regex: help for improvement
3 direct replies — Read more / Contribute
by frazap
on Dec 14, 2018 at 02:45
    I have names all composed of ascii characters, that I need to uniformize:
    • remove non letter (',.)
    • replace "-" by a space
    • start each word with an upper case
    • break camel case word: dosSantos -> Dos Santos

    I came with the code below that seems to work (as far as I can test it).

    My questions: how could I improved it ? (I think it will break if with unicode characters, what changes should I made to get it work with any character set ?)

    Thanks

    François

    use strict; use warnings; while ( my $t = <DATA> ) { chomp $t; printf "orig: %-30s translated: %s\n", $t, translate($t); } sub translate { my $str = shift; $str =~ tr/-/ /; #replace - with a space $str =~ tr/a-zA-Z/ /cs; #replace non letter with a space my @words = split( /\s+/, $str ); foreach my $w (@words) { #insert a space when a upper case is inside a word if ( $w =~ /\p{isLower}\p{isUpper}/ ) { my @all; while ( $w =~ m/\G(\p{isUpper}*\p{isLower}+)/g ) { push @all, $1; } $w = join( " ", @all ); } else { $w = ucfirst( lc($w) ); # we are using side effect of fore +ach loop } } return join( ' ', @words ); } __DATA__ Acierno James S., Jr. Acierno James, Jr. Ackermann-Hirschi L. Agatonovic-Jovini T. Alba-Castro Jose-Luis Alconada Verzini M. J. AlconadaVerzini M. J. Alvarez Fernandez A. Alvarez-Bolado Gonzalo Alvarez-Gonzalez B. AlvarezGonzalez B. AlvarezPiqueras D Amor Dos Santos S. P. Amor DosSantos S. P. AmorDosSantos S. P da Costa F. Barreiro Guimaraes Dano Hoffmann M. DanoHoffmann M. Dell' Acqua A. Dell' Asta L. Dell'Acqua A. Dell'Asta L. Dell'Omo Giacomo della Volp D. della Volpe D. Della Volpe D. DeRegie J. B. De Vivie Derendarz D. deRenstrom P. A. Bruckman Dupl'akova Nikoleta Duplakova Nikoleta Faucci Giannelli M. Fauccigiannelli M. FaucciGiannelli M. Yusuff I. Yusuff' I. Yao W-M Yao W-M. Yao W. -M Yao W. -M.
how to isolate text in a text file.
6 direct replies — Read more / Contribute
by undergradguy
on Dec 13, 2018 at 21:05
    Hello monks. I am an undergrad that has started to teach myself Perl from scratch. I know nothing about coding or any thing similar but this has grabbed my attention. So I come to you this day to seek your knowledge and guidance. I have a text file that has a DNA string in it. I want a way to isolate the DNA string and ignore the rest of the text file. Is this possible? Thank you for your time.
Mojolicious global variable
1 direct reply — Read more / Contribute
by bartrad
on Dec 13, 2018 at 14:53

    Evening monks, I'm after some of your wisdom.

    I have a Mojolicious lite app that works as I would expect for a single user. However, if two users are accessing it at the same time, the value of $router is changing depending on who submitted the request last.

    For example, if user A submits the form to query 'RouterA' then the information is displayed for that router. However, when user B then submits the form to query 'RouterB', the session for user A and user B displays the information for 'RouterB'. I figure it must be since I am declaring $router (and other things) globally but I'm not sure how to store this and pass it around the different routes I have...

    my ( $router, $cfg, $ip ); get '/' => sub { my $c = shift; $c->render( template => 'index' ); }; post '/' => sub { my $c = shift; ($router) = $c->param('router'); app->log->info("Router $router"); $cfg = get_config($router); $ip = $cfg->get_ip(); $c->render( template => 'result', router => $router, ip => $ip, ); } => 'index'; get '/info' => sub { my $c = shift; $c->render( template => 'result', router => $router, ip => $ip, ); }; get '/cards' => sub { my $c = shift; my %cards = $cfg->get_cards(); $c->render( template => 'cards', router => $router, cards => \%cards + ); }; app->start;

    The reason I have globally declared the variables is so I can pass them between the different routes and have the value of $router preserved and displayed on each resultant HTML page. Any help greatly appreciated as I'm scratching my head with this one!

Net::SSH::Perl and Net::SSH::Perl::Agent
2 direct replies — Read more / Contribute
by arc444
on Dec 13, 2018 at 14:16

    Hi. Can anyone advise how I can get my Net::SSH::Perl object to use a particular key I have identified in my Net::SSH::Perl::Agent object ?

    I have deliberatley simplified down - I will actually iterate over all available keys until I find the one I want ( based on 'comment' ) and then wish to use that particular key

    Im unable to try all keys as my target host only allows a few attempts, and I have many keys loaded into the agent ( reducing these available keys is not an option )

    Many Thanks !

    # Ensure the invoking process has a valid ssh-agent running, and is lo +aded with an appropriate key, or keys use warnings; use strict; use Net::SSH::Perl::Key; use Net::SSH::Perl::Agent; my $agent = Net::SSH::Perl::Agent->new(2); my ($key, $comment) = $agent->first_identity; use Net::SSH::Perl; my $ssh_user = 'myuser'; my $ssh_host = 'myhost'; ## How to use the above referenced $key in the following ssh connectio +n ?? ## my %ssh_params = ( debug => '1', options => [ "StrictHostKeyChecking n +o", "UserKnownHostsFile /dev/null" ] ); my $ssh = Net::SSH::Perl->new( $ssh_host, %ssh_params ); my $result = $ssh->login("$ssh_user"); if ( $result ) { print "Logged in as ${ssh_user} on host ${ssh_host}\n"; } else { print "Failed to login in as ${ssh_user} on host ${ssh_host}\n"; }
Perl launching process
6 direct replies — Read more / Contribute
by pwagyi
on Dec 13, 2018 at 05:17

    Greeting monks! I have been using perl system, backtick for some time to invoke other executables. But then I came across IPC::Cmd run, run_forked, I realize that it's somewhat better in a sense that I can easily access stdout, stderr and also exit code. So the question is when is it appropriate to use each system, backtick, or other modules? Is there best practice?

Net::SSH2 error - Username/PublicKey combination invalid
1 direct reply — Read more / Contribute
by BernieC
on Dec 12, 2018 at 21:05
    I'm back playing with Net::SSH2 and running into trouble again. My code is still the very very simple
    my $ssh2 = Net::SSH2->new() ; $ssh2->connect(HOST) or $ssh2->die_with_error ; $ssh2->check_hostkey(tofu => HOSTKEY) or $ssh2->die_with_error ; $ssh2->auth_publickey(USER, PUBLICKEY, PRIVATEKEY) or $ssh2->die_with_error ; $ssh2->auth_ok() ;

    Here's what's happening: I have a real SSH client that uses a single SSH keyprofile for two different unix systems. I've double checked and the and authorized.keys files on both servers are identical. I have the two constants: HOST and USER. when I changed the HOST and USER to be the new system and the username to use on that system, I get

    Username/PublicKey combination invalid (-18 LIBSSH2_ERROR_PUBLICKEY_UN +RECOGNIZED ) at D:\Perl\ondreamhost.pl line 28.
    I have no idea what it is trying to tell me. What do usernames have to do with SSH keys?
folding Data::Dumper output
3 direct replies — Read more / Contribute
by morgon
on Dec 12, 2018 at 18:04
    Hi,

    sometimes I have the problem of having to look at large Data::Dumper or json dumps.

    With json I can simply load them into vim and with "foldmethod=syntax" I can easily fold them and so navigate easily the hierarchies of large documents.

    Unfortunately I have yet to figure out how to fold Data::Dumper output in vim in a similar way.

    Does someone have a tip here?

    Many thanks and sorry for posting a question that may more pertain to vim than to perl...

Killer byte tripping up Perl?
4 direct replies — Read more / Contribute
by echo5
on Dec 12, 2018 at 17:22

    I have a simple script that appears to show that some byte in the output is causing Perl to behave strangely.

    The script calls a command that coughs up 150 bytes or so of binary data. One stream of returned data behaves as expected. Another stream causes chaos.

    The script: $cmd = "/usr/local/bin/mycmd"; print "The cmd to be run is: $cmd \n"; open(CMD, "$cmd |" ) or die "Can't run '$cmd'\n$!\n"; while (<CMD>) { chomp; print "My raw output is: $_ \n"; $dataout = $_; print "My DATAOUT is: $dataout \n"; }

    When I run the above script in a "good" scenario I get the below output:

    The cmd to be run is: /usr/local/bin/mycmd My raw output is: &#65533; ` /11&#65533;%_$&#65533;%f$&#65533;&c$&#65 +533;%a$&#65533;%\$&c$&^$&#65533;&i$ My DATAOUT is: &#65533; ` /11&#65533;%_$&#65533;%f$&#65533;&c$&#65533; +%a$&#65533;%\$&c$&^$&#65533;&i$

    When I run the above script in a "bad" scenario I get the below output:

    The cmd to be run is: /usr/local/bin/mycmd My raw output is: My DATAOUT is: My raw output is: &#65533;0]&#65533;c &#65533;&#65533; My DATAOUT is: &#65533;0]&#65533;c &#65533;&#65533;

    Ultimately the goal is to ingest the data and process it using unpack but that was failing as $_ didn't contain data is should contain to process. The "bad" behavior above seems to show that there is some sort of "killer byte" being output from mycmd that throws a wrench into things. Below is the good and bad output in hex form via xxd. Is there a byte in there tripping up Perl?

    Good data stream: 0000000: 0202 00d0 0000 0000 0000 0000 0100 0000 ................ 0000010: 0100 0000 0100 0000 0100 0000 0100 0000 ................ 0000020: 0100 0000 0100 0000 0500 0000 0500 0000 ................ 0000030: 0500 0000 0500 0000 0500 0020 0100 0000 ........... .... 0000040: 0100 0000 0100 0000 0100 0000 0100 0000 ................ 0000050: 0100 0000 0100 0000 0500 0000 0500 0000 ................ 0000060: 0500 0000 0100 0000 0100 0000 0000 0000 ................ 0000070: 0200 0060 0100 0020 0000 0000 0100 2d00 ...`... ......-. 0000080: 0100 2f00 0100 3000 0000 0000 0100 0000 ../...0......... 0000090: 0000 0000 0102 ca25 0102 4a24 0102 bd25 .......%..J$...% 00000a0: 0102 5024 0102 da25 0102 4c24 0102 d525 ..P$...%..L$...% 00000b0: 0102 4c24 0102 c325 0102 4624 0102 e025 ..L$...%..F$...% 00000c0: 0102 4e24 0102 e225 0102 4824 0102 dd25 ..N$...%..H$...% 00000d0: 0102 5224 ..R$
    Bad data stream: 0000000: 020a 009c 0000 0000 0000 0000 0100 0000 ................ 0000010: 0100 0000 0100 0000 0100 0000 0100 0000 ................ 0000020: 0100 0000 0100 0000 0100 0000 0500 0000 ................ 0000030: 0500 0000 0500 0000 0500 0000 0500 0000 ................ 0000040: 0500 0000 0500 0000 0500 0000 0500 0000 ................ 0000050: 0500 0000 0500 0000 0500 0000 0500 0000 ................ 0000060: 0500 0000 0500 0000 0100 0000 0000 0000 ................ 0000070: 0100 3000 0000 0000 0100 005c 0100 00b4 ..0........\.... 0000080: 0000 0000 0100 0000 0000 0000 0200 0063 ...............c 0000090: 0100 0020 0000 0000 0103 9206 0103 8506 ... ............

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.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others pondering the Monastery: (3)
    As of 2018-12-15 05:22 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      How many stories does it take before you've heard them all?







      Results (69 votes). Check out past polls.

      Notices?