Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

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
Array from list in input file?
2 direct replies — Read more / Contribute
by SandraA
on Nov 24, 2015 at 16:13
    I have a file containing three columns of strings (the last one is a numeric value) I want a code that prints the string in the first column for every line where the third value is above a certain threshold. My first idea was to open the file and treat the values as an Array with Three scalars, split the scalars and ask perl to print the first one if the third one was larger than my threshold. I don't know if that is a good way to do it, and anyway I have no idea how to write it. Could anyone help me solve my problem?
efficient IPv6 subnetting
2 direct replies — Read more / Contribute
by Anonymous Monk
on Nov 24, 2015 at 16:06

    Hello all, I'm trying to calculate and print out all subnets of prefix length x from a subnet with a prefix length y \. For example: I want to split a /40, say 2001:0DB8::/40 into /56 subnets. I thought about using NetAddr::IP , for example:

    use NetAddr::IP; my $sub6 = new NetAddr::IP '2001:db8::/40'; my $i=1; while ($sub6 < $sub6->broadcast) { # should've been <= but it does no +t seem to work if ($i==4722366482869645213696) { # that many addresses in a / +56 print "ip = $sub6\n"; $i=1; } $sub6 ++; $i++; } print "ip = $sub6\n"; # need to print last address

    the above probably works but seems so inefficient and terribly slow. Any ideas would be greatly welcomed!

Doubly link list implementation
7 direct replies — Read more / Contribute
by punitpawar
on Nov 24, 2015 at 14:24
    Hello , I am struggling to write code to implement a doubly link list. Could any of you please help me with it. This is what I have written so far. If you could point me to any material which shows how a doubly linked list is implemented in PErl that will be of great help to me...
    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $head= undef; ## reference to first node my $tail=\$head; ## reference to the "next" field of the last node my $list; open FILE, "<datastored.txt" or die $!; # Creating a doubly linked list while (<FILE>){ my $node = { "data" => $_ , "next" => undef, "prev" => undef, }; $$tail=$node; $node->{"prev"}= $tail; $tail = \$node->{"next"}; } print Dumper $head; &print_list($head); sub print_list { $list=$_[0]; while ($list) { print Dumper $list; print "$list->{data}"; $list = $list->{next}; } }
Split with numbers
3 direct replies — Read more / Contribute
by Anonymous Monk
on Nov 24, 2015 at 13:23
    Hello, I have a set of strings that may be made of up to three parts: "LETTERS_BEFORE"+"NUMBER"+"LETTERS_AFTER".
    For example AB23C ABC23 23BC ABC.
    Is there a way to split them into an arrays of 3 elements?
    The operation on previous strings should produce ('AB','23','C'), ('ABC','23',''), ('','23','BC'), ('ABC','','').

    Thank you in advance for any hint.
PTKDB - exception catched Not a SCALAR reference
1 direct reply — Read more / Contribute
by pjkang7
on Nov 24, 2015 at 12:13

    Hi all, So, I'm pretty sure this is an issue (or just process of) with perl ptkdb debugger tool that I use, I wanted to see if anyone has experienced similar issue. The error message I get is like this: ptkdb - >>> exception catched Not a SCALAR reference at (eval 49) line 4.

    and I believe this occurs from the following line of code

    my %hash = (); my $h_ref = \%hash; if(exists $$h_ref{'try'}) {

    I'm pretty sure my dereferencing of the hash reference is correct, and I think it's simply something catched by the ptkdb tool (happens when I do step by step using the tool). The script actually executes correctly without an error if run normally. I just wanted to see if perlmonks knew of this issue (if anyone uses ptkdb) and that I can safely simply ignore this. Thank you!! Happy Thanksgiving!!

CGI of url-encoded query string
2 direct replies — Read more / Contribute
by glendeni
on Nov 24, 2015 at 00:00

    On a website I run I've recently noted in the apache error logs a number of url-encoded requests ala

    GET /cgi-bin/script.cgi?c%3D1%3Bu%3D1%3B...
    which causes the script to fail, whereas using the comparable query string
    GET /cgi-bin/script.cgi?c=1;u=1;...
    is successful. My website uses perl v5.8.0 and apache 2.0.46, but I tested this on my less dated home server using perl 5.18.2 and apache 2.4.7 with the same result.

    The perl script uses

    use CGI ; my $query = new CGI; $cparam = $query->param('c'); $uparam = $query->param('u');
    Should this be happening? I had assumed the CGI module would handle url-encoded input. Is there a way to treat this?

    I should add that the url-encoded cases are very rare and may come from some kind of bot instead of a human user.

    LATER - decided that the submitted query string is invalid and should not be expected to be processed by CGI since query string delimiters have been encoded, making parsing of parameter name and value impossible. Will now try to delete this post, but leaving this in case I can't figure that out

How to make parent wait for all the child processes.
3 direct replies — Read more / Contribute
by gjoshi
on Nov 23, 2015 at 23:11
    Hello All,

    I Am forking child processes. I am waiting for them to finish in parent. If you see my code What I want to parent is not to move forward until it get info from each child. Next portion of the code is dependent on the status of the child. I want to do kind of wait in a loop in parent and keep checking for the child's response. Here is my problem I am not able to do it last logic. Please help me with suggestions.

    #!/usr/local/bin/perl -w use strict; use warnings; use Net::Telnet; use IO::Socket::INET; my $IsParent = 1; my $ListenPort = 5000; my $PPID = $$; print "I am the only process.\n"; my @children_pids; for my $count (1..3){ my $child_pid = fork(); if ($child_pid) { # If I have a child PID, then I must be the + parent push @children_pids, $child_pid; } else { # I am the child # close the sides of the pipes not used by the child my $end; local $SIG{HUP} = sub { $end = 1 }; my $Child_PID = $$; print "\n============================== \n"; print "CHILD's PID is: $Child_PID \n"; my $db1 = ConnectToServer('',$ListenPort,60); local $SIG{HUP} = sub { $end = 1 }; #Do something and then write to DB as done WriteValueToDB('done',$db1,$Child_PID . '_Status'); until ($end) { #print "Sleep 1\n"; sleep 1; } print "============================== \n"; function2(); } } foreach my $child (@children_pids) { print "Parent: Waiting on $child\n"; sleep 5; waitpid($child, 0); } # HERE I WANT TO GET THE STATUS OF ALL THE KIDS BECAUSE FROM HERE IT D +EPENDS ON EACH RESULT FURTHER PROCESSING. WAIT IN A LOOP OR SOMTETHIN +G # NOT GETTING IT HOW TO DO IT. I DON'T WANT TO CONTINUE UNLESS I GET A +LL KIDS STATUS. DON'T WANT TO GO TO END DB MAIN UNLESS I GET ALL CHIL +D PROCESSES STATUS. # my $localtime = localtime; # my $child_stat = ReadValue($child . '_Status',$dbmain); # accoding to the result in DB decide to kill it #print "$child CHILD STAT: $child_stat \n"; #kill HUP => $child; print "END DB MAIN: $dbmain \n"; KillServer($dbmain); print "All done.\n";
Function Prototypes
6 direct replies — Read more / Contribute
by KimberTLE
on Nov 23, 2015 at 20:18
    Having difficulty coming-up with what the prototype for my sub might look like. If coded as is (below), the sub works; the caller sends named parameters, the sub checks for useful data, does the caller's bidding. A sample of things I've tried for prototypes are:
    sub ConfigRead($ @ %); sub ConfigRead(;$ @ %); sub ConfigRead($ \@ \%); sub ConfigRead(;$ \@ \%);
    My actual code without the prototype resembles this:
    #!/usr/bin/perl -w use strict; my @aFieldHeaders; my %hFieldConfigs; my $sConfigFile = 'mydata.csv'; ConfigRead(sFILE => $sConfigFile, apHEAD => \@aFieldHeaders, hpFIELDCONF => \%hFieldConfigs); # my array and hash now have some cool stuff in 'em! sub ConfigRead { my %hArgs = ( sFILE => 'BAD', # lazy user alert! whine & die apHEAD => 'BAD', # ^^^ see comment above hpFIELDCONF => 'BAD', # by now you know the drill! @_, # user demands come from here ); # stick some cool stuff in their variables }
    Suggestions, solutions and/or winning lottery ticket numbers for Wednesday's drawing gratefully accepted!
do-until inside while loop control
3 direct replies — Read more / Contribute
by mtorba
on Nov 23, 2015 at 18:48
    Hi PerlMonks,

    I did not figure out how to solve this question after take a look in the main discussion lists.

    I have a data_file like this one:

    regex1 - grab general informations about regex1

    grab more informations on this line about regex1

    grab more informations on this line about regex1

    grab more informations on this line about regex1

    grab more informations on this line about regex1

    grab more informations on this line about regex1


    grab more informations on this line about regex1

    regex2 - grab general informations about regex2

    grab more informations on this line about regex2

    grab more informations on this line about regex2

    grab more informations on this line about regex2

    grab more informations on this line about regex2

    grab more informations on this line about regex2


    grab informations on this line

    regex3 - grab general informations about regex3

    grab more informations on this line about regex3

    grab more informations on this line about regex3

    grab more informations on this line about regex3

    grab more informations on this line about regex3

    grab more informations on this line about regex3



    I'm using a do-until inside a while loop:

    while<data_file> { if(/regex1/) { get some general informations about regex1 do { get more informations in lines between regex1 e regex2 } until(/regex2/) } }
    It works, but it returns to while loop in the first line after regex2. So, I cannot check for regex2 and get general informations about it. Thanks for any help.
using Linux getdents syscall
5 direct replies — Read more / Contribute
by glasswalk3r
on Nov 23, 2015 at 18:37

    Hello monks,

    I'm looking for a fast way to list the contents of a directory (with thousands of files) on Linux by using Perl.

    I did some research on that and found a sample C code that uses the getdents system call for that. By using it, one can avoid calling stat on each file inside the directory (basically what ls command does).

    I did some tests with readdir, but performance speed compared to the already mentioned C code as good. That said, I'm inclined to try to use Perl syscall to do the same. Below is the C code (for those inclined to read it):

    This is how the C struct should look like:

    struct linux_dirent { unsigned long d_ino; /* Inode number 32*/ unsigned long d_off; /* Offset to next linux_dirent 32*/ unsigned short d_reclen; /* Length of this linux_dirent 16*/ char d_name[]; /* Filename (null-terminated) */ /* length is actually (d_reclen - 2 - offsetof(struct linux_dirent, d_name)) */ }

    Since I'm not a C programmer, I struggling to achieve that. I found that I need to use unpack to retrieve the information from the related C struct, but I'm lost about:

    • Finding out the lenght I need to setup the Perl equivalent to the buffer (a scalar set with NUL characters, as my $buffer = "\0" x 64;), specially because the related C structure has a char array with dynamic length
    • The buffer will retain a N number of dentries inside of it. How can I find the exactly number of bytes each dentrie has and how can I jump from one entry to the other with Perl?

    Is it even possible to do that without having to use XS (or any of it's alternatives)? I found Convert::Binary::C to give a hand, but probably I'm not using it correctly due the 2 issues above. If I use Data::Dumper on the buffer, I can see the file names, but got only garbage from Convert::Binary::C.

    Here is my (not working) Perl code implementation:


    Alceu Rodrigues de Freitas Junior
    "You have enemies? Good. That means you've stood up for something, sometime in your life." - Sir Winston Churchill

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 browsing the Monastery: (8)
    As of 2015-11-25 07:14 GMT
    Find Nodes?
      Voting Booth?

      What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

      Results (672 votes), past polls