Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

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
http post
2 direct replies — Read more / Contribute
by bigup401
on Feb 19, 2017 at 09:18

    i got some issue when i execute my code i get this Response Code: 411

    #!/usr/bin/perl use strict; use HTTP::Request::Common qw(POST); use LWP::UserAgent; my $ua = new LWP::UserAgent; my $senderid = "demo"; my $num = "447777777777"; my $sms = "demo"; my $rep = HTTP::Request->new(POST => " +s/send/?apiKey=edftr44456&message=$sms%20HTTP%20API&from=$senderid&to +=$num"); $rep->content_type("application/x-www-form-urlencoded"); $rep->content_type("Content-Type' => 'application/json"); my $repobj = $ua->request($rep); my $repcode = $repobj->code; print 'Response code: ' . $repcode . "\n";
Perl 6 OOP: before and after methods "CLOS style"
2 direct replies — Read more / Contribute
by Anonymous Monk
on Feb 18, 2017 at 18:37

    I'm learning Perl 6 and I'm constantly blown away by amazing Perl 6 features, it's something I experienced only while I was learning a bit of Common Lisp.

    I wish to know if in the Perl 6 MOP there is something similar to CLOS before/around/after methods.

    Also, given that my experience with programming is mainly quick procedural scripts (and, sadly, one big system in classic asp and vb for work) , which books/resources can give me a good grasp of Perl 6 OOP philosophy? For CL I loved the CLOS book by Kleene, but Perl 6 approach seems different (Smalltalk-ish???).

    Thank you very much for your wisdom.

To splice or not to splice? What implementation is more readable, efficient, etc.?
6 direct replies — Read more / Contribute
by vr
on Feb 18, 2017 at 12:33

    I'm asking for advice on style, rather than how to solve a problem. How a professional would do it? What's readable to others -- and myself, in a year? So, all answers are maybe just opinion based and are welcome :-).

    There's usual complex data structure AoHoAH... , not very deep. We can assume root is

    $root = { value => [ ... ]};

    Two types of array elements are "interesting":

    { type => 'items', value => [ ... ]} # and other key-value pairs { type => 'foo', value => { ... }} # and other key-value pairs

    "Items" hash "points to" another array and is to be processed recursively. "Foo" hash is to be checked and may be replaced (split) with several hashes. Other "uninteresting" elements can be anything (but always hashrefs) and are to be left "as is".

    The next sub is to be called as foobar( $root ), and hopefully will do everything right:

    sub foobar { my $href = shift; $href-> { value } = [ map { foobar( $_ ) if $_-> { type } eq 'items'; $_-> { type } eq 'foo' ? SPLIT_FOO( $_ ) : $_ } @{ $href-> { value }}]; }

    Or even shorter, moving a check out of sight:

    sub foobaz { my $href = shift; $href-> { value } = [ map { foobar( $_ ) if $_-> { type } eq 'items'; SPLIT_IF_FOO( $_ ) } @{ $href-> { value }}]; }

    The next sub has slightly less "punctuation noise" and skips assignment, and is to be called fooqux( $root-> { value }), i.e. now arrayref can serve as "root" instead of structure above.

    sub fooqux { $aref = shift; splice @$aref, 0, @$aref, map { fooqux( $_-> { value }) if $_-> { type } eq 'items'; SPLIT_IF_FOO( $_ ) } @$aref }

    What I'm not sure about all these, is they always rebuild any array within original structure, even if there's no "foo" elements at all. With condition checking moved to SPLIT, the SPLIT_IF_FOO is always called for all elements, regardless. Next sub prevents these shortcomings, but uses Perl's "no-no" -- the C-style loop.

    sub fooquux { $aref = shift; for ( my $i = 0; $i < @$aref; $i ++ ) { my $item = $aref-> [ $i ]; fooquux( $item-> { value }) if $item-> { type } eq 'items'; next unless $item-> { type } eq 'foo'; my @list = SPLIT_FOO( $item ); splice @$aref, $i, 1, @list; $i += $#list } }

    And, not sure what's worse, to splice potentially many times or to always replace with new array. Or maybe there's "best" idiomatic way to solve such problem?

Set env variables as part of a command
2 direct replies — Read more / Contribute
by devilock76
on Feb 18, 2017 at 12:13

    Ok so to real quick this I am not the most experienced perl programmer having only dug into it as needed. And well recently I needed it for something

    So I have a script doing a series of system updates for a large user base. The only guarantee I have is solaris 10, unidata installed, and perl 5.10 or greater. Part of what I need to do is run some scripts against the unidata data. Withour JDBC installed for unidata it leaves me with a command line option only for getting a short data set and running a few other commands against it.

    So in typical the command would look something like this

    (cd $unidatadir;udt $command)

    Running in a subshell is the cleanest way to do this IMO because of the cd to the directory requirement. The problem is in order to do it properly the environment variables DASP and DASU need to be set which are for an encrypted password and username respectively.

    So right now my command also before the cd is setting the env variables for the subshell.

    I guess what I am wondering if anyone has a perhaps cleaner way to do this as it seems slightly fragile to me for when it is distributed

Extracting regex from string
4 direct replies — Read more / Contribute
by mleshin
on Feb 18, 2017 at 00:44

    After parsing a file and extracting the following line-
    my $string = "hello $1";
    # print $string = 'hello $1

    I would like to apply this string as a regexp replacement. For example-
    if ("good morning all" =~ /good morning (\w+)/) {
    print $string;
    # I would like to be written 'hello world add'

Send control break in PERL
1 direct reply — Read more / Contribute
by Anonymous Monk
on Feb 18, 2017 at 00:40

    I want to execute one of the commands in a router, where the command won't display anything, to be more clear, here is the command

    router> monitor traffic interface ae10 matching "tcp port 179" size 1500 write-file capture.pcap

    when you issue the above command, here is the response from the router

    Address resolution is ON. Use <no-resolve> to avoid any reverse lookup delay. Address resolution timeout is 4s. Listening on ae10, capture size 1500 bytes

    In the above output for the command " monitor traffic interface ae10 matching "tcp port 179" size 1500 write-file capture.pcap", it will listen for some packet and store in pcap file, the command will/should stop only when we send CTRL_C

    I tried one internal command, of our company, here is the following code and error

    $rh2->cmd(mode=>'cli', cmd=>"monitor traffic interface ae10 ma +tching \"tcp port 179\" size 1500 write-file capture.pcap"); $rh2->send_control_char(char=>'CTRL_C', timeout=>2400);

    the code gives the following error

    Feb 17 21:26:35 [INFO ] [sherlock.1] [cmd] monitor traffic interface a +e10 matching "tcp port 179" size 1500 write-file capture.pcap Feb 17 21:27:35 [ERROR] [sherlock.1] JT::Device::_send: No pattern mat +ched during 'monitor traffic interface ae10 matching "tcp port 179" s +ize 1500 write-file capture.pcap' from patterns: [ '-re', '^(?:{(?:ma +ster|backup)(?:.*)}[\r\n]*)?(?:\[edit[^\]]*\]\s+)??JT_53_sherlock:\s* +' ] Feb 17 21:27:35 [ERROR] [sherlock.1] Device did not respond as expecte +d.Please refer the expect file Feb 17 21:27:35 [ERROR] Expected patterns are : -re ^(?:{(?:master|bac +kup)(?:.*)}[\r\n]*)?(?:\[edit[^\]]*\]\s+)??JT_53_sherlock:\s*

    Is there a way to solve this using any perl commands

Discard if present within other coordinate range
3 direct replies — Read more / Contribute
by jnarayan81
on Feb 17, 2017 at 17:36

    I need a solution for following computing problem for millions of ids. I have list of followings ids (sample)

    SEQ1 225 275 SEQ1 200 300 SEQ1 201 299 SEQ1 250 399 SEQ1 145 244 SEQ2 120 130 SEQ2 100 150 SEQ2 101 149 SEQ2 120 230 SEQ2 99 140

    I want to remove/discard those ids-range which completely fall within others range, and keep the rest.

    In other word, it should print the following ids

    SEQ1 200 300 SEQ1 250 399 SEQ1 145 244 SEQ2 100 150 SEQ2 120 230 SEQ2 99 140
Processing JSON with Perl
2 direct replies — Read more / Contribute
by DanielSpaniel
on Feb 17, 2017 at 14:42

    I seem to be having troubles and misunderstandings with processing JSON. My difficulty is likely in large part due to the fact that I don't really seem to understand the variable structures properly.

    So, I have a JSON file, and I've a script which is using the JSON module, and I've decoded the data, etc, and now have a little loop where I want to work my way through the file and print it out. However, although I can print a few bits from the top level of the structure, I'm having problems trying to access anything else. FYI the JSON file is data retrieved from one of the wikimedia sites, but it seems valid.

    The relevant Perl code is immediately below, while the JSON file data, as output by Dumper is below that:

    my $data=decode_json($rawdata); # print Dumper($decoded); for ( @{ $data->{sections} } ) { # This line works; prints the 4 titles (one from each section) print $_->{title}."\n"; # No image info' in file anyway, so no output expected, but not sure i +f code is correct for ( @{ $_->{images} } ) { print $_."\n"; } # Nothing gets printed, but no error (figure it should print something + from top section) print $_{content}->{text}."\n"; # This fails with "Not a hash reference" # for ( @{ $_->{content}->{elements} } ) # { # print $_->{text}."\n"; # } }
    The JSON data, as output by Dumper, is below: (text edited for readability, so it fits nicely)
    $VAR1 = { 'sections' => [ { 'images' => [], 'level' => 1, 'content' => [], 'title' => '10-minute Turkey' }, { 'images' => [], 'level' => 2, 'content' => [ { 'text' => 'Makes 4 servings.', 'type' => 'paragraph' } ], 'title' => 'Description' }, { 'images' => [], 'level' => 2, 'content' => [ { 'elements' => [ { 'elements' => [], 'text' => 'abc' }, { 'elements' => [], 'text' => 'efg' }, { 'elements' => [], 'text' => 'hij' }, ], 'type' => 'list' } ], 'title' => 'Ingredients' }, { 'images' => [], 'level' => 2, 'content' => [ { 'elements' => [ { 'elements' => [], 'text' => 'tuv' }, { 'elements' => [], 'text' => 'wxy' }, { 'elements' => [], 'text' => 'z12' }, ], 'type' => 'list' } ], 'title' => 'Directions' } ] };

    The actual URL I'm retrieving, for testing, is:

    So, I don't really seem to get how to access anything which is at a lower level, such as {sections}->{content}->{elements}->{text}, or {sections}->{content}->{text}. I'm also a bit confused as to how to distinguish, programatically, between the two bottom sections (i.e. "Directions" and "Ingredients"); for instance, how, if I only wanted "text" fields from the latter, could I distinguish it, in code, from the former (i.e. the third section, titled "Ingredients"?

    Any assistance would be most welcome.

Strawberry/ActiveState Perl 5.24.1 - Invalid parameter - -R error when invoking perldoc
3 direct replies — Read more / Contribute
by pritesh_ugrankar
on Feb 17, 2017 at 14:11


    The following error is noticed when I installed either strawberry perl or activestate perl and invoke perldocs:

    Invalid parameter - -R

    I tried re installing several times, still the same error. I did google but could not find anything affirmative or a workaround. Am I missing something or doing something wrong?

Excel Button to Run Perl
3 direct replies — Read more / Contribute
by rd48sec
on Feb 17, 2017 at 14:01
    Still new to PERL. I have an Excel workbook cell that contains data I want to pass to a PERL script. I want to just push a button in the worksheet that passes the cell value to my PERL script, and run the script. Thank you for any starting point.

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

    How do I use this? | Other CB clients
    Other Users?
    Others contemplating the Monastery: (4)
    As of 2017-02-19 18:58 GMT
    Find Nodes?
      Voting Booth?
      Before electricity was invented, what was the Electric Eel called?

      Results (293 votes). Check out past polls.