Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
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
Generate list of possibilities from incomplete input
3 direct replies — Read more / Contribute
by Pascal666
on Jan 20, 2018 at 19:25

    Given a string containing 9 hexadecimal characters, I need to generate a list of all possible 10 character hexadecimal strings that contain the given 9 characters in order. The list need not be in any specific order.

    I think the complete list will have 16x10=160 items, but 9 of those will be duplicates. Don't worry about removing the duplicates, but if your solution doesn't include them that is fine too.

    Obviously, this can be done with a couple nested loops and string concatenation. Somehow, that just doesn't feel like the best way to me though.

    For example, given 0ae4bb830, the list would include:

    00ae4bb830 10ae4bb830 20ae4bb830 30ae4bb830 40ae4bb830 50ae4bb830 60ae4bb830 70ae4bb830 80ae4bb830 90ae4bb830 a0ae4bb830 b0ae4bb830 c0ae4bb830 d0ae4bb830 e0ae4bb830 f0ae4bb830 00ae4bb830* 01ae4bb830 02ae4bb830 03ae4bb830 04ae4bb830 ...
    *Duplicate
What does Test::LeakTrace do?
1 direct reply — Read more / Contribute
by TerryBerry
on Jan 20, 2018 at 16:53

    Could you nice folks clarify what Test::LeakTrace does and what problems it finds? I wonder if I misunderstand because it's giving me errors for very, very simple code. Or maybe there are some very simple things about Perl I've been doing wrong all these years. You decide (then tell me).

    Consider this code:

    #!/usr/bin/perl -w use strict; use Test::LeakTrace; # test for leak leaktrace { require './AlmostEmpty.pm'; };
    AlmostEmpty.pm is, well, almost empty:
    1;
    Here's the output from running the script:
    leaked SCALAR(0x558ad5e37f40) from ./dev.pl line 7.

    It seems weird to me to get any kind of memory leak for such a very basic script.

    Here's my perl version:

    This is perl 5, version 26, subversion 0 (v5.26.0) built for x86_64-li +nux-gnu-thread-multi (with 56 registered patches, see perl -V for more detail)

    I'm running on Ubuntu Linux 17.10.

Multiple params
2 direct replies — Read more / Contribute
by htmanning
on Jan 20, 2018 at 15:05
    Monks,

    I'm missing something here. I have a link with 2 params, (cell and target_dir).

    use CGI qw(:standard); use CGI 'param'; $store = new CGI; $cell = $store->param('cell'); $target_dir = $store->param('target_dir');

    The link looks like this: http://domain.com/script.pl?cell=123&target_dir=/usr/me/attachments/

    All I get from the script is the target_dir. I'm not getting the cell returned. What am I doing wrong?

Excel or Perl for simple statistics?
2 direct replies — Read more / Contribute
by Anonymous Monk
on Jan 20, 2018 at 08:22
    Dear Monks,
    I want to do a few basic statistics (mean and stdev) and since I have lots of data I figured I would do it with Perl (using the Statistics::Basic module). However, I notice some quite interesting discrepancies as opposed to if I calculated the same values using Excel's formulas. Particularly I think the stdev is a problem, since in one test run I did, I got 0.401 with Excel and 0.41 with the Perl module, which does affect my calculations later on.
    Do you have any comment on that?
POST API in Perl using LWP::UserAgent with authentication providing errors
2 direct replies — Read more / Contribute
by ssara
on Jan 20, 2018 at 06:32

    Hello, I am trying to use POST method in perl to send information to an API. I would like to call the below api which requires following inputs:

    URI: https://www.cryptopia.co.nz/api/GetBalance

    Input:

    Currency: (optional) The currency symbol of the balance to return e.g. 'DOT' (not required if 'CurrencyId' supplied)

    CurrencyId: (optional) The Cryptopia currency identifier of the balance to return e.g. '2' (not required if 'Currency' supplied).

    Request Structure:

    REQUEST_SIGNATURE: API_KEY + "POST" + URI + NONCE + HASHED_POST_PARAMS

    API_KEY: Your Cryptopia api key

    URI: the request uri. e.g. https://www.cryptopia.co.nz/api/GetBalance

    HASHED_POST_PARAMS: Base64 encoded MD5 hash of the post parameters

    NONCE: unique indicator for each request.

    Below is my code snippet:

    use LWP::UserAgent; use JSON; use Digest::MD5 qw(md5); use Digest::SHA qw(hmac_sha256_base64); use MIME::Base64; my $api_key ='PUBLIC KEY'; my $api_private_key ='PRIVATE KEY'; my $ua = LWP::UserAgent->new; my $url = "https://www.cryptopia.co.nz/api/GetBalance"; my %req = ( Currency => "PAC" ); my $nonce = int(rand(1000000)); my $post_data = encode_json(\%req); my $post_data_enc = encode_base64(md5($post_data)); my $req_signature = sprintf("%sPOST%s%s%s", $api_key, lc(urlencode($ur +l)), $nonce, $post_data_enc); # Sign request signature with private key. my $req_signature_hmac = hmac_sha256_base64($req_signature, decode_bas +e64($api_private_key)); # Generate value for 'Authorization' header field. my $auth_header_value = sprintf("amx %s:%s:%s", $api_key, $req_signatu +re_hmac, $nonce); my $response = $ua->post($url, Content => $post_data, 'Content-Type' => 'application/json', 'charset' => 'utf-8', Authorization => $auth_header_value ); die "Request failed: ", $response->content unless $response->is_succes +s(); print $response->content, $/; sub urlencode { my $s = shift; $s =~ s/ /+/g; $s =~ s/([^A-Za-z0-9\+-])/sprintf("%%%02X", ord($1))/seg; return $s; }

    This code gives the following error: {"Success":false,"Error":"Signature does not match request parameters."}.

    I have also checked the PUBLIC and PRIVATE key and it works when i use a java or php code. But when I am doing with perl it just provides me error. Please can you help me on providing pointers.

    Thank You in advance.

CGI.pm POST_MAX not working
4 direct replies — Read more / Contribute
by adjuvant
on Jan 19, 2018 at 15:37

    I've been searching the web and playing with my code for a while now and can't find a solution to this problem.

    I would like to limit uploads to my site with CGI. I'm setting $CGI::POST_MAX = 1024 * 1024 * 20; for a 20 Mb limit, but when I test it with a 900 Mb file, the upload goes through just fine. I've tried every modification I can think of including moving the $CGI::POST_MAX statement around, changing use CGI; to use CGI qw( :standard ); and updating CGI.pm using CPAN. I now have version 4.38 of CGI.pm installed. I would welcome any ideas to be able to protect my server from DDoS attacks.

    Here is my code snippet:

    #!/usr/bin/perl -T my $version = "0.1"; use strict; use warnings; use CGI; use CGI::Carp qw/fatalsToBrowser/; $CGI::POST_MAX = 1024 * 1024 * 20; # maximum upload filesize is 20M $| = 1; my $q = CGI->new; print $q->header; print $q->start_html(-title=>"mysite", -style=>{-src=>'/plasma/style.css'}); print $q->start_multipart_form(-method=>'POST', -action=>'/cgi-bin/start_analysis.cgi') +; print $q->filefield(-name=>"uf_core", -size=>20); print "\tFile type: "; print $q->popup_menu(-name=>"urt", -values=>['fasta','genbank'], -default=>'fasta'); print "<br><br>"; print qq{<input type="file" name="uf_qry" size="20" multiple="true" /> +}; print "<br>"; print $q->submit(-value=>"ANALYZE!"); print $q->end_multipart_form; print $q->end_html;
    Thanks!
How to strip comments and whitespace from a regex defined with /x?
5 direct replies — Read more / Contribute
by jh
on Jan 19, 2018 at 14:27

    I would like to print out some previously-defined regular expressions in a compact format. The main thing I want to do is strip out the whitespace and comments from those defined with the /x modifier. So if I have two functionally identical regexes:

    our $rgx_plain = qr/^([a-z]+)\d*$/; our $rgx_fancy = qr/ ^ # beginning of string ( # begin cap $1 [a-z]+ # one or more letters ) # end cap $1 \d* # optional digits $ # end of string /x;

    then I'd like to make a function clean_regex such that

    say $rgx_plain; say clean_regex($rgx_fancy);

    both print the same thing. Ideally clean_regex is a no-op on regexes defined without the /x modifier, such that

    say clean_regex($rgx_plain);

    also prints the same thing. I have hacked together something gross and terrible but I was hoping for something better, presumably asking the Regexp compiler what it has once it's done throwing away comments and whitespace.

    Thanks!

LWP::UserAgent POST example
2 direct replies — Read more / Contribute
by ssara
on Jan 19, 2018 at 12:44

    Hello, I am trying to use POST method to send information to an API.Please can you provide me an example on how to use it.

    I would like to call the below api which requires following inputs:

    URI: https://www.cryptopia.co.nz/api/SubmitTrade

    Input Parameters are:-

    Market: The market symbol of the trade e.g. 'DOT/BTC' (not required if 'TradePairId' supplied)

    TradePairId: The Cryptopia tradepair identifier of trade e.g. '100' (not required if 'Market' supplied)

    Type: the type of trade e.g. 'Buy' or 'Sell'

    Rate: the rate or price to pay for the coins e.g. 0.00000034

    Amount: the amount of coins to buy e.g. 123.00000000

    Please can you tell me how I can call this api from perl ?

    Thank You in advance!!

Send an email attachment
2 direct replies — Read more / Contribute
by AmyB
on Jan 19, 2018 at 12:35
    I'm attempting to modify an existing mailsend program to be able to send a file attachment and need some new ideas. I'm not proficient in PERL at all, so please reply in detail.
    #!/usr/bin/perl -w use strict; # for stronger code my $numargs = $#ARGV + 1; if (($numargs > 3) || ($numargs < 1)) { print "usage : mailsend.pl <logfile> [subject] -t\n"; print "syntax : <logfile> is required. [subject] is optional. [-t] specifies to send a copy to maileater\n"; print "example: mailsend.pl /tmp/test.log\n"; print "example: mailsend.pl /tmp/test.log Test!\n"; print "example: mailsend.pl /tmp/test.log Test! -t\n"; exit; } use Net::SMTP; # net SMTP module my($smtp) = Net::SMTP->new('inesg2.alliance.lan',Debug => 1); $smtp->mail('aixreport@countryfinancial.com'); my $host = `uname -a | cut -d " " -f2`; # my $emseater = 't_ca_mailtrigqa@countryfinancial.com'; my $emseater = 'amy.blass@countryfinancial.com'; my $sendto = 'amy.blass@countryfinancial.com'; my $subject; chomp ($host); my $logfile = $ARGV[0]; chomp ($logfile); if ($numargs > 1) { $subject = $ARGV[1]; } else { $subject = join ": ", $host, $logfile; } my $message = `cat $ARGV[0]`; $smtp->data(); $smtp->datasend("Subject: ". $subject . "\n\n"); $smtp->datasend($message); if ((($numargs == 3) | ($numargs == 4)) && ($ARGV[2] eq "-t")) { $smtp->to($emseater); my $emsfile= '/home/unixadmin/emsmksysb.txt'; # $smtp->datasend("MIME-Version: 1.0\n"); # $smtp->datasend("Content-Type: application/text; name=$emsfile +\n"); $smtp->datasend("Content-Disposition: attachment; filename=\"$ +emsfile\"\n"); # print $smtp ; ## system("ls -l"); ## $smtp->datasend("Content-type: text/plain; name=\"$emsfile\"\+ +n"); } else { $smtp->to($sendto); } $smtp->dataend(); $smtp->quit; The basic part of the PERL that is changing is the if ((($numargs == 3 +) section. I've done basic debugging to know it's getting into that + section. My current debug output is the following: root@x1aix500.countrylan.net/>perl mailsend.pl '/home/unixadmin/emsmks +ysb.txt' 'junk' -t Net::SMTP>>> Net::SMTP(2.29) Net::SMTP>>> Net::Cmd(2.26) Net::SMTP>>> Exporter(5.58) Net::SMTP>>> IO::Socket::INET(1.29) Net::SMTP>>> IO::Socket(1.29) Net::SMTP>>> IO::Handle(1.25) Net::SMTP=GLOB(0x201fd5d8)<<< 220 mail1.countryfinancial.com ESMTP Pro +xy Server Ready Net::SMTP=GLOB(0x201fd5d8)>>> EHLO localhost.localdomain Net::SMTP=GLOB(0x201fd5d8)<<< 250-mail1.countryfinancial.com Hello x1a +ix500.countrylan.net [10.78.196.91], pleased to meet you Net::SMTP=GLOB(0x201fd5d8)<<< 250-ENHANCEDSTATUSCODES Net::SMTP=GLOB(0x201fd5d8)<<< 250-PIPELINING Net::SMTP=GLOB(0x201fd5d8)<<< 250-8BITMIME Net::SMTP=GLOB(0x201fd5d8)<<< 250 STARTTLS Net::SMTP=GLOB(0x201fd5d8)>>> MAIL FROM:<aixreport@countryfinancial.co +m> Net::SMTP=GLOB(0x201fd5d8)<<< 250 2.1.0 Sender ok Net::SMTP=GLOB(0x201fd5d8)>>> DATA Net::SMTP=GLOB(0x201fd5d8)<<< 503 5.5.1 Need RCPT (recipient) Net::SMTP=GLOB(0x201fd5d8)>>> Subject: junk Net::SMTP=GLOB(0x201fd5d8)>>> this is a test of the attachment system +under EMS. Net::SMTP=GLOB(0x201fd5d8)>>> . Net::SMTP=GLOB(0x201fd5d8)<<< 500 5.5.1 Command unrecognized: "Subject +: junk" Net::SMTP=GLOB(0x201fd5d8)>>> RCPT TO:<amy.blass@countryfinancial.com> Net::SMTP=GLOB(0x201fd5d8)<<< 500 5.5.1 Command unrecognized: "" Net::SMTP=GLOB(0x201fd5d8)>>> Content-Disposition: attachment; filenam +e="/home/unixadmin/emsmksysb.txt" Net::SMTP=GLOB(0x201fd5d8)>>> . Net::SMTP=GLOB(0x201fd5d8)<<< 500 5.5.1 Command unrecognized: "this is + a test of the attachment system under EMS. " Net::SMTP=GLOB(0x201fd5d8)>>> QUIT Net::SMTP=GLOB(0x201fd5d8)<<< 500 5.5.1 Command unrecognized: "."
    Any help would be great?
Returning columns with SQL::Statement error
3 direct replies — Read more / Contribute
by LalakisOeisagwmenos
on Jan 19, 2018 at 10:28

    Hello, I am sorry for bothering you but trying to execute the paradigm of SQL::Statement::Structure on a Strawberry perl v5.21.1 I had the following error.

    Can't call method "name" on unblessed reference
    The code is the following:
    use SQL::Statement; use Data::Dumper; my $sql = "SELECT a,aa FROM b JOIN c WHERE c=? AND e=7 ORDER BY f D +ESC LIMIT 5,2"; my $parser = SQL::Parser->new(); $parser->{RaiseError}=1; $parser->{PrintError}=0; # $parser->parse("LOAD 'MyLib::MySyntax' "); my $stmt = SQL::Statement->new($sql,$parser); printf "Command %s\n",$stmt->command; printf "Num of Placeholders %s\n",scalar $stmt->params; printf "Tables %s\n",join( ',', map {$_->name} $stmt->tab +les() ); printf "Where operator %s\n",join( ',', $stmt->where->op() ); printf "Limit %s\n",$stmt->limit(); printf "Offset %s\n",$stmt->offset(); printf "Columns %s\n",join( ',', map {$_->name} $stmt->col +umn_defs() );
    Output

    Can't call method "name" on unblessed reference at c:\Users\PasvantidisR\Documents\scripts\perl\test_sql_statement.pl line 17.

    Command SELECT
    Num of Placeholders 1
    Tables b,c
    Where operator AND
    Limit 2
    Offset 5

    Can you please help? Thank you Lalakis Oeisagwmenos

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 all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others perusing the Monastery: (2)
    As of 2018-01-21 05:43 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      How did you see in the new year?










      Results (227 votes). Check out past polls.

      Notices?