Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

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
Comments detected in strings
1 direct reply — Read more / Contribute
by astroboy
on Oct 20, 2014 at 17:09
    Hi all - I'm trying to identify comments in code (so that ultimately I'll strip them out). I've tried using Regexp::Common::comment, but it appears to detect comments in strings when they should really be ignored. Am I using it wrong, or is it a limitation of the module?
    use strict; use Regexp::Common qw /comment/; my @tests = ( { language => 'PL/SQL', description => 'PL/SQL Comment in String', code => q{ declare j varchar2(2); begin j := '--'; end; } }, { language => 'PL/SQL', description => 'PL/SQL no comment', code => q{ declare j varchar2(2); begin j := 'xx'; end; } }, { language => 'SQL', description => 'SQL Comment in String', code => q{ select '--' from dual; } }, { language => 'SQL', description => 'SQL no comment', code => q{ select 'xx' from dual; } }, { language => 'Perl', description => 'Perl Comment in String', code => q{ my $j = '#'; } }, { language => 'Perl', description => 'Perl no comment', code => q{ my $j = 'xx'; } } ); foreach my $test (@tests) { print $test->{description}."\n"; if ($RE{comment}{$test->{language}}->matches($test->{code})) { print "\tcontains comment\n"; } else { print "\tno comment\n"; } }
    which outputs:
    PL/SQL Comment in String contains comment PL/SQL no comment no comment SQL Comment in String contains comment SQL no comment no comment Perl Comment in String contains comment Perl no comment no comment
Net::FTP::Recursive - how to use rls
2 direct replies — Read more / Contribute
by zalezny
on Oct 20, 2014 at 15:29
    Hi All, on the beginning warm welcome to every one. Since few hours I`m trying to use Net::FTP::Recursive to list recursively all files on the some FTP server. At the moment its not possible for me because for some reason filehandler doesnt work for rls method. Maybe somebody will be able to help me here and solve my issue.
    #!/home/tom/scripting/perl5/bin/perl use Net::FTP::Recursive; use warnings; use strict; use FileHandle; my $ftp = Net::FTP::Recursive->new("", Debug => 1); $ftp->login("anonymous",'me@here.there'); $ftp->cwd('/'); open FH,"> rlist.db"; my @ftpfiles; @ftpfiles = $ftp->rls(<FH>); print @ftpfiles; $ftp->quit;
    I would like to be able to print output from $ftp->rls to screen and if its possible save it to file. It seems that I dont understand perl "filehandle". Maybe somebody will be able to help me here pasting working solution. FTP server is public(Centos mirror). How to list all files with using "rls" command on that server ? Thanks in advance for Your support. Zalezny
Saving .cgi Output; Passing File As Argument?
3 direct replies — Read more / Contribute
by Ragged Robin
on Oct 20, 2014 at 13:22
    Hey guys, I have a pretty big script that makes a lot of print calls at various points to generate an html output -- is there anyway I can have the output save to the server automatically each time this is ran? If this was a more simple script I could just push the print statements to "whatever > /dir/name.html" but in this case that's not really an option.

    I thought about making a system call to run the script again at the end, however I'm not sure if this is able to be done due to the nature of the input which is a file (users go to an .html front end page and then select the file to upload which is used for the script input). I tried something like:

    system("perl /dir/script.cgi parametername='/dir/file' > /dir/output.html");

    However the output html file I get just gives me my invalid file message so it doesn't look like it takes the input in that way. Is there a better way to approach this or should I be able to pass a file as a parameter in the system perl call?
Problem with monitoring running tasks
1 direct reply — Read more / Contribute
by cariddiEMC
on Oct 20, 2014 at 13:04

    Hi, I am pretty new to perl, so please be understanding. Below is a perl subroutine, that I inherited, that is used to run a set of "X" tests simultaneously. This subroutine is called by a script that I will call that takes a file containing a list of tests and runs them. Periodically I am finding that for some reason or another 1 or more of the tests we run do not complete. Each test has a timeout that will terminate the test if exceeds the time limit.

    When I use system monitor to see what is going on, none of my tests are running anymore, but I see 2 or more instances of running. Every instance of, except 1, that are running, have a pid that relates to the test or tests that have not completed. I am assuming that pid of the process that I cannot match up is the pid of the terminal window where I originally ran from.

    Can somebody help me find what is wrong? I have done a lot of reading on waitpid and on the other commands used in the runall subroutine but I have not found any smoking gun.

    Thanks. Mark

    sub runAll { my $self = shift; my $doneThreadsLock : shared = 1; my $testQueueLock : shared = 1; my @workers; for (1..$self->{'maxtasks'}) { push @workers, threads::async { $SIG{'INT'} = sub { my $tid = threads->tid(); # Tell user we've been terminated if (exists $self->{'runningTasks'}->{$tid}) { my $worker_task = $self->{'runningTasks'}->{$t +id}; my $exec_name = getExecName(join(" ",@{$worker +_task->{'command'}})); my $pid = $worker_task->{'pid'}; kill(-12, $pid); # print "Worker $tid >> Waiting$exec_name pid: +$pid\n"; waitpid($pid, 0); # print "Worker $tid >> Done $exec_name pid: $p +id\n"; $worker_task->{'endTime'} = time(); } { lock $doneThreadsLock; $self->{'doneThreads'}->enqueue($tid); } print "INT: Worker $tid exiting\n"; threads->exit(); }; my $tid = threads->tid(); my $rc; my $continueProcessing = 1; my $worker_task; while ($continueProcessing) { { lock $testQueueLock; $worker_task = $self->{'testQueue'}->dequeue(); } if(!$worker_task) { $continueProcessing = 0; next; } my $exec_name = getExecName(join(" ",@{$worker_task->{ +'command'}})); chdir ($worker_task->{'workdir'}); print "Running: $exec_name\n"; $worker_task->{'startTime'} = time(); $self->{'runningTasks'}->{$tid} = $worker_task; my $cmd = join(" ", @{$worker_task->{'command'}}); my $pid = fork; # if we are child process, pid will be 0 otherwise we +are the master if ($pid == 0) { # print "pid = 0, $exec_name running as child proce +ss.\n"; my $logfile = FileHandle->new; $logfile->open("> $worker_task->{'log'}"); $logfile->autoflush(1); open(STDOUT, '>&=' . $logfile->fileno); open(STDERR, '>&=' . $logfile->fileno); select STDERR; $| = 1; # make unbuffered select STDOUT; $| = 1; # make unbuffered $logfile->close; # print "Execing child process $exec_name pid($pid) +.\n"; { lock $doneThreadsLock; $self->{'doneThreads'}->enqueue($tid); } setpgrp; exec("$cmd"); exit(1); } $worker_task->{'pid'} = $pid; my $child_status; # print "Waiting for $exec_name $pid to exit\n"; while (waitpid($pid, POSIX::WNOHANG) != -1) { $child_status = $?; sleep(1); } # print "Done waiting for $exec_name $pid to exit\n"; $worker_task->{'endTime'} = time(); $worker_task->{'status'} = $child_status; # print "Done waiting for $exec_name $pid to exit statu +s ($child_status)\n"; } { lock $doneThreadsLock; $self->{'doneThreads'}->enqueue($tid); } threads->exit(); }; } print "all tasks queued, Now waiting for tasks to exit before queu +ing more.\n"; { lock $testQueueLock; $self->{'testQueue'}->enqueue(undef) for @workers; } my $threads_exited = 0; my $stop_done = 0; while ($threads_exited < $self->{'maxtasks'}) { my $tid; { lock $doneThreadsLock; $tid = $self->{'doneThreads'}->dequeue_nb(); } if (defined($tid)) { threads->object($tid)->join(); $threads_exited++; print "threads_exited($threads_exited) maxtasks:($self->{' +maxtasks'}).\n"; } else { if ($self->{stop} && !$stop_done) { $stop_done = 1; foreach my $thr (threads->list()) { $thr->kill('INT'); } } else { sleep(1); } } } }
Iteratively unpack structure from binary file
1 direct reply — Read more / Contribute
by cMonkE
on Oct 20, 2014 at 12:58
    Perl Monks, I humbly seek your wisdom:

    I wish to unpack a series of strustures from a binary file. I have used:

    @array = unpack("f*", join('',<$filehandle>));
    to load an array of floats into memory from a smaller binary file, but
    a) This file is too big to fit in memory
    b) It has a complex structure, like "int, int, float, float, float" repeating.

    How shall I iteratively unpack the next structure from the file into a list of scalars, without loading the whole file into memory?

Debugging a Web Application
No replies — Read more | Post response
by ron_abraham
on Oct 20, 2014 at 10:38
    HI Monks,
    This question is more for knowledge sake, than for a practical problem i am facing .
    Currently for any debugging purposes, i use logging with the useful LogDispatch plugin for my session based CGI::Application.
    If the need were to arise, and i need to monitor variables and run time performance of individual lines of code being executed , is there any way i can go about it .
    I am aware of Devel::NYTProf which i heard about at perl monger discussions, but i want to know if i can get a user manual/blog post on how to setup a run time debugger for perl web scripts with any graphic ide and a hook to a web server.
    My current environment is Eclipse(Aptana IDE) with EPIC which does have a debugger , but i cant seem to get it working. I tried using Padre, and i faced some issues with the Debug client which i have logged on the wiki.However i still cant confirm if the homegrown Padre IDE has a webserver hook.
Perltidy indents too much when there are stacked opening tokens
No replies — Read more | Post response
by will_
on Oct 20, 2014 at 09:56
    Perltidy seems to think that this code:
    sub discover { return [ { 'name' => $name, 'version' => $VERSION, } ]; }
    ...would look better like this (I disagree):
    sub discover { return [ { 'name' => $name, 'version' => $VERSION, } ]; }
    It's indenting the hash keys twice, presumably because there are two opening tokens. I'm using -sot "stack opening tokens".
    But surely a large benefit of stacking opening parentheses and brackets is that you don't have to indent twice?
    It's saving vertical space but wasting horizontal space.

    Does anyone know the setting to control this? I've looked through the docs but not found it:
Can Perl write multiple files at the same time?
4 direct replies — Read more / Contribute
by westrock2000
on Oct 20, 2014 at 09:33
    I have a bunch of USB drives attached to my computer that I use as backup. Currently files are written sequentially and it takes a while. Is there a way to tell Perl to write 6 files each to separate drives at the same time?
combining emacs' cperl-mode formatting with Perltidy
1 direct reply — Read more / Contribute
by LanX
on Oct 20, 2014 at 08:33

    I love the instant formatting features emacs gives me when typing Perl, but they can't cope with perltidy's detailed control.

    So I would like to run perltidy from time to time to update my text buffer (anything less frequent than with every return hit)

    Problem is to have a compatible and "tolerant" config, where both formatter don't start messing the result of the other one.

    Did anyone already try to achieve this somehow?

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)

Why does perltidy mess up whitespace before inline comments and equals?
2 direct replies — Read more / Contribute
by will_
on Oct 20, 2014 at 07:17
    At work we've recently tried to agree on a set of perltidy rules. We came up with these:
    -i=4 # 4 character indents in blocks -pt=2 # "horizontal tightness" -wls='=>' # ensure there's always space to the left of => -wrs='=>' # and always to the right of => -vtc=0 # always break before a closing token -l=79 # 79 characters wide please -nolc # no "outdenting" for long comments - indent them properly -nolq # no "outdenting" for long quotes/strings -sot # stack opening tokens - same as -sop -sohb -sosb -sct # stack closing tokens
    But they seem to result in unexpected changes like this:
    - error(300) if $@; # 300 = GSI_BAD_ID + error(300) if $@; # 300 = GSI_BAD_ID
    and this:
    my $d; $d->{status} = 'queued'; $d->{description} = 'The action was successfully queued'; - $d->{id} = '12345'; # Identifies action request + $d->{id} = '12345'; # Identifies action request

    So my questions are:
    1) What's the point of these changes?
    2) Which options control them?

    I read the docs but did not find anything relevant:

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!
  • 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
  • Outside of code tags, you may need to use entities for some characters:
            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 scrutinizing the Monastery: (12)
    As of 2014-10-20 22:00 GMT
    Find Nodes?
      Voting Booth?

      For retirement, I am banking on:

      Results (92 votes), past polls