Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
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
pipe list open trouble?
1 direct reply — Read more / Contribute
by dk
on Sep 30, 2014 at 09:01
    Hello all,

    Can anybody explain why I'm seeing the difference in those pieces of code? I thought these should be identical:

    $ perl -e 'open F, @ARGV or die $!' '|-' echo 42 No such file or directory at -e line 1. $ perl -e 'open F, $ARGV[0],$ARGV[1],$ARGV[2] or die $!' '|-' echo 42 42
    Thank you!
timelocal error wired behaviour
3 direct replies — Read more / Contribute
by Anonymous Monk
on Sep 30, 2014 at 02:44
    Hi Monks,

    I am getting a date input from a csv file, which i want to check each date with current date, and if older than 1 month, i can do some operation on it for that entry.

    I am not allowed to install extra libs so, i am not using Date::Calc and have to somehow stick to Time::Local.

    Here is the snippet of my code, and suggest where I am going wrong.

    Code :

    if (my ($inpmm, $inpdd, $inpyyyy) = @date[1] =~ '(\d+)/(\d+)/(\d+)') { { print "@date[1] : Has been split to $certyyyy, $certmm, $certdd"; my @certdate=(0, 1, 1, $certdd, $certmm-1, $certyyyy); print "---@certdate"; # Just to see how it gets formed my $inptime=timelocal_nocheck(@certdate); print "<td>$inptime</td>"; my $timediff=$inptime - $lmtime; print "$timediff"; if ($timediff <= 2628000) { <<Go with Job>> } else { <<Skip Job>> } } else { print "Not in Format" }

    Output

    08/12/2016 : Has been split to 2016, 08, 12---0 1 1 12 7 2016

    After this, it ubruptly ends, even when i have some 100 odd entries to go.

    Thanks a lot in advance

String::MkPasswd still supported?
5 direct replies — Read more / Contribute
by Skeeve
on Sep 30, 2014 at 01:25

    Recently I needed a function to generate passwords so instead of writing my own I did a CPAN search and found String::MkPasswd.

    Unfortunately the function simply increases the number of lower case letters if you don't give enough minimum characters of each class. Example: If you want at least 2 lower case letters and 2 upper case letters and 8 characters length, you always end up with 2 upper case and 6 lower case letters.

    I think this isn't too good so I created a pull request which will spread the missing 4 characters over all character classes.

    Now I'm wondering whether or not the module is still supported as there seems to be nothing happening.


    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Style in CGI Header
1 direct reply — Read more / Contribute
by Anonymous Monk
on Sep 29, 2014 at 23:42
    I have code that prints html header this way with CGI.pm:

    -style => {-code=> "$page_style", 'src'=>[$_css_path,$_css_path2]},#.. +.. I just copied that line out...

    this is just part of it that goes in this header:
    print start_html();

    My question is, if I have a page that I want to pull in a different CSS is there a way to put them all in a array instead of the way I did it, where the files are all printed into there so they are all pulled in:
    @whatever = ("$_css_path","$_css_path2"); -style => {-code=> "$page_style", 'src'=>@whatever}, #....
    Then if I have another path, say in this tag: $_css_path3, how would I add it? push?

    Please let me know how to make it work.
    Thank you. :)
    Ukn
Hash of subroutines as member of a class
3 direct replies — Read more / Contribute
by Hameed
on Sep 29, 2014 at 21:18
    Hi PerlMonks,

    It maybe a simple thing, but I seem to have hit a brick wall.

    I have a very simple class and in the constructor, I am creating a hash that is holding references to subs which are members of the same class as well.

    see below:
    package EOYStats; use strict; use warnings; use Data::Dumper; sub new { my $class = shift; my $this = bless {}, $class; $this->{ACT} = shift; %{ $this->{ACTIVITIES} } = ( 'Sale' => { 'func' => \&total_sold, 'datefield' => "date_sold", }, 'Purchae' => { 'func' => \&total_bought, 'datefield' => "date_bought", }, ); return $this; } sub get_stats { my $this = shift; my $arg = shift; $this->{ACTIVITIES}->{$this->{ACT}}->{'func'}->($arg); } sub total_sold { my $this = shift; my $arg = shift; $this->dosomething(); } sub total_bought { my $this = shift; my $arg = shift; # Do stuff.... } sub dosomething { my $this = shift; print "This is test...\n"; } return 1;
    Now, when I call total_sold from another method in this class (get_stats in this case), '$this' is undefined in total_sold and '$this->dosomething' returns an error 'Can't call method "dosomething" on an undefined value at EOYStats.pm line 37.'

    There is no real need to have these methods in a hash. I can simply write conditions in the get_stats and call the methods accordingly, but I wanted to try and see if this worked.

    so is it really ridiculously bad idea to do this or is it not possible or simply silly thing to do?

    Sorry if this is too confusing.

Running a perl script as a system command in another thread hangs while main thread reading from STDIN
1 direct reply — Read more / Contribute
by rmahin
on Sep 29, 2014 at 20:14

    Hi perlmonks, have run into a weird issue. In this program, the main thread is reading from STDIN, and other threads are issuing system commands in the background. The weird part is that it only seems to cause a problem when the system command is a perl command. Have tested this on Windows 7 and Windows 2012 R2.

    This is not the original code I found, but a simplified script that I hope adequately demonstrates the issue. If the script is run with input, it simply executes echo hello world, if it is given input it will run perl -e "print \"hello world\""

    My hunch would be that reading from STDIN is preventing perl from performing the fork, which would make sense if it had this problem with all system commands but it seems to be limited to perl, or something else that I am not seeing. My first thought was to close STDIN in the thread, but this didn't seem to make any difference. Hopefully one you has some idea of whats going on here :/

    This yields the following output

    Thanks for taking a look!

    UPDATE: Including perl -v output. This is the same for both 2012 systems that are affected by this issue. Other operating systems seem to be unaffected.

    C:\>perl -v This is perl 5, version 18, subversion 2 (v5.18.2) built for MSWin32-x +64-multi-thread (with 1 registered patch, see perl -V for more detail) Copyright 1987-2013, Larry Wall Binary build 1801 [297964] provided by ActiveState http://www.ActiveSt +ate.com Built Feb 24 2014 11:06:47 Perl may be copied only under the terms of either the Artistic License + or the GNU General Public License, which may be found in the Perl 5 source ki +t. Complete documentation for Perl, including FAQ lists, should be found +on this system using "man perl" or "perldoc perl". If you have access to + the Internet, point your browser at http://www.perl.org/, the Perl Home Pa +ge.
cgi redirect
2 direct replies — Read more / Contribute
by mitchreward
on Sep 29, 2014 at 16:47

    hi monks

    I got a small perl-cgi script that has to run and redirect to another web page. But therefore I print the cgi headers an http response is already sent back, and a 2nd one get to a 500 error.

    I've googled and searched on the Seekers of Perl Wisdom but can't find any way to do my redirect once executed

    #!/usr/bin/perl use CGI qw(:standard); use strict; my $cgi = new CGI; print $cgi->header(); my @values = $cgi->param('option[]'); foreach (@values) { my $command=`rm -r /media/dde/video/$_`; print $command; } #$cgi->redirect( -location=>"train1.htm");

    thanks

try to connect to Linux
1 direct reply — Read more / Contribute
by digioleg54
on Sep 29, 2014 at 16:43

    Below ismy script:

    #!/usr/bin/perl -w use strict; use Net::SSH2::Perl; my $host = "10.160.12.26"; my $sshusername = "mktftp"; my $sshpasswd = "markdb"; print "Start\n"; my $ssh = Net::SSH2::Perl->new($host, debug => 1, protocol => 2); print "Before login\n"; my $loginStatus = $ssh->login($sshusername,$sshpasswd); print "After login\n"; my $command = "date"; my $stdout; my $stderr; my $exit; eval { ($stdout,$stderr,$exit) = $ssh->cmd($command); }; if ($@) { if ($@ =~ m/Permission denied/i) { print "Authentication failed\n"; exit 1; } } print "$stdout\n";

    when I run it, show error:

    Can't locate Net/SSH2/Perl.pm in @INC (you may need to i rl module) (@INC contains: C:/Strawberry/perl/site/lib C /lib C:/Strawberry/perl/lib .) at C:\\conn.pl line 4. BEGIN failed--compilation aborted at C:\\conn.pl line 4.

    Could you please tell me why? I am trying to connect from Windows 7 to Linux

open and read file using cgi perl
2 direct replies — Read more / Contribute
by vivek.vivek
on Sep 29, 2014 at 11:29

    Hi, I have 2 files as below

    a.txt: LOCK xxx yyy 123 1.1 fff LOCK nnj hhh 789 2.2 uuu
    b.txt: LOCK xxx yyy 567 1.1 fff LOCK nnj hhh 000 2.2 uuu LOCK YUI hhh 520 2.3 ujk

    I am comparing both files by browsing it through a webpage and parsing the file. I need to compare the lines if only it starts with word LOCK and output the data. The code is doing the comparison, but my problem is that the output is repeated with the count of number of lines in each file.

    Eg: if a is compared with b, output repeted twice. if b is compared with a, output is repeated 3 times.

    my @files = ($file,$file1); open(INOUT1,"<", $file1) or die "cant open output file "; + while ($linea = <INOUT1>){ open(INOUT,"<", $file) or die "cant open output file"; while ($line = <INOUT>){ chomp $linea; next unless $linea =~ m/^LOCK /; chomp $line; next unless $line =~ m/^LOCK /; foreach $file_n (@files){ $old = $files[0]; $new = $files[1]; if ($old eq $file_n){ @words=split(/\s+/,$line); $feature1[$i]=$words[1]; $ver1[$i]=$words[3]; $exp1[$i]=$words[4]; $no1[$i]=$words[5]; $i++; } else{ @words=split(/\s+/,$linea); $feature2[$ii]=$words[1]; $ver2[$ii]=$words[3]; $exp2[$ii]=$words[4]; $no2[$ii]=$words[5]; $ii++; } } }close INOUT; }close INOUT1; print "<table border =1 align='left' style='font-family:Georgi +a;'> for ($b=0;$b<@feature1;$b++) { $test=0; for($a=0;$a<@feature2;$a++) { if($feature1[$b] ne $feature2[$a]) { $test++; } if($test == @feature2) { print "<tr><td>$feature1[$b]</td><td>$ +ver1[$b]</td><td>$exp1[$b]</td><td>$no1[$b]</td></tr>"; #$test++; } } } print "</table>"; print "<table border=1 align='left' style='font-family:Georgia +;'> for ($b=0;$b<@feature2;$b++) { $test=0; for($a=0;$a<@feature1;$a++) { if($feature2[$b] ne $feature1[$a]) { $test++; } if($test == @feature1) { #print $test; print "<tr><td>$feature2[$b]</td><td>$ver2 +[$b]</td><td>$exp2[$b]</td><td>$no2[$b]</td></tr>"; } } } print "</table>";}
Do I need to use Coro instead of threads/forks
2 direct replies — Read more / Contribute
by mohan2monks
on Sep 29, 2014 at 06:37

    Hi monks i am here again to seek your wisdom..

    I have a cgi script (which i am trying to turn into psgi app Change cgi script to PSGI app) which has to connect to different vendor api's and collect data and return in as a json/xml output

    I am trying to fetch this data simultaneously from each vendor by creating threads for each vendor.
    I need to create max 10 threads.
    But now vendor api has changed and i will have to make additional api calls in each thread.
    Example Call a vendor api get list of products then fetch details of each over a api call with product id.
    If i start threads again in a thread already it crashes and memory increases too, plus i need to load too much modules (may be i don't know how to do it correctly)

    I have been searching perlmomks and net for probable alternatives and found that as my script usually wastes lot of time in waiting for SOAP::Lites calls i may be better off with using Coro instead of threads. (one of the reference Why Coro?)
    Again by reading on perlmonks i changed to using forks/forks::BerkeleyDB (forgive me i don't have reference to this now).
    It worked fine till it was not needed to use threads in already running threads. If i fork again foreach product apache has too many children.
    I actually tried it on a test system and my admin is not nice to me since :(

    Can i safely use Coro to do this?
    I am a bit confused about how to explicitly use Coro's cede function.(where to put it exactly inside threads) If i cede it inside a thread will that thread run again?
    Will all my vendor functions that i start in main thread run in parallel?
    I have read http://http://search.cpan.org/~mlehmann/Coro-6.41/Coro.pm this in details but i am confused.

    Please enlighten me..

    #!/usr/bin/perl #use forks::BerkeleyDB; #use threads; use strict; use Coro; use CGI qw(:standard); use XML::Simple; use JSON qw(encode_json); use MIME::Base64 qw(encode_base64); use DBI; use SOAP::Lite; use Data::Dumper; use CHI; my (@req,@odata,@errdet)=(); my %threads=(); foreach my $vnd (@req){ #$threads{$vnd}=threads->create({ 'context' => 'list', 'exit' +=> 'thread_only' },\&startthread,$vnd,$SCH); $threads{$vnd}=async{&startthread($vnd,$SCH) }; } cede; foreach my $vnd (keys %threads) { my($err,$data) =$threads{$vnd}->join(); if ($err eq 'N') { push @odata,@{$data}; } }elseif($err eq 'Y'){ push @errdet,$data; }elsif($threads{$vnd}->error) # with threads it was useful, { push @errdet,{ Vnd=>$vnd, ErrorCode=>26,ErrorMsg=>$threads +{$vnd}->error}; } } sub startthread { my ($vendor,$SCH)=@_; my($err,$data) =(); require './'.$vendor.'functions.pl"; #load vendor specific code ($err,$data)=&getvendordata($SCH); return($err,$data); } #vendor functions has somewhat code like this besides functions specif +ic to each vendor api sub getvendordata { my $SCH=shift; #perform vendor specific tasks mostly SOAP::Lite calls to api #Has to perform multiple calls some of them depend on output of pr +evious calls #Also have to make simultaneous calls which may not be related to +each other can be done parallelly. #e.g. first call to api returns a list of products subsequent call +s to fetch details. #If i start threads/forks again here most of the time program cras +hes :( my ($err,@data)=(); my @products=getproduects(); #Maybe i can start coro routines here to get all listed detail +s simultaneously foreach my $product (@products) { #fetch product details over api push @data,$product->getdetails; } return ($err,\@data); }

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!
  • 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?
    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 surveying the Monastery: (12)
    As of 2014-09-30 17:11 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      How do you remember the number of days in each month?











      Results (378 votes), past polls