Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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
Series of REGEX with OR
4 direct replies — Read more / Contribute
by wrkrbeee
on Apr 27, 2016 at 13:05

    Hi Perl Monks, have a series of regexs that work great until I impose a series of OR conditions. I receive an error stating "use of uninitialized value for $url_sub at line 45." Excluding the OR series eliminates the error, so I'm not sure how the ORs create an error. Grateful for any ideas. Thanks!

    while (my $line = <$FH_IN>) { chomp $line; #removes line break or new line; my $url_sub = ""; print "processing file $counter,\n"; # Within each record, loop until a match occurs with "subsid" in the r +ecord,; # and the record contains a URL address, and the URL contain a derivat +ive; # of Exhibt 21, e.g., ex21, ex-21, exhibit21, or exhibt-21; + while ($line =~ m/subsidiar/igm && $line =~ m/\/Archives(.* +)">/igm && ($line =~ m/ex21/igm || $line =~ m/EX\-21/igm || $line =~ m/exhibit\-21/igm || $line =~ m/exhibit21/i +gm) ) { $url_sub = $1; #extract the match and assign to var +iable; #Join the match with the standard URL prefix; my $url = join("",$base_url,$url_sub); print $url; open my $FH_OUT, '>>',$write_dir or die "Can't open fi +le $write_dir >:$!>"; print $FH_OUT "$url\n"; ++$counter; } #End of while loop for extracting matching text; } #End of record;
Read Directory and getlines in .csv
3 direct replies — Read more / Contribute
by Anonymous Monk
on Apr 27, 2016 at 10:57

    Hello. I am new to Perl and programming. I have written a perl program to get the names of .csv files in a different directory which were uploaded to the server today only, by modified date. These files are 13+ MB so I don't want to copy and move them to my new directory. I also wrote another perl program which will read a file and get only the lines with what I want and place those lines in a .csv with the criteria I need for my final report. My question is: How do I integrate these two programs into one program without moving these large files from the directory they are housed in. Is this possible?

    #This is the program to get the .csv file names from the directory: #!/usr/bin/perl use strict; use warnings; use File::stat; use Text::CSV_XS; use IO::File; my $dirname = "Daily_QoS_CPD_link"; opendir(DIR, $dirname) or die "Not able to open $dirname $!"; # Create an array, Open the directory, get only .csv's modified in the + last 24 hours my @dir = sort { -M "$dirname/$a" <=> -M "$dirname/$b"} grep /\.csv/, $dirname ne '.' && $dirname ne '..', readdir + DIR; rewinddir(DIR); # create a list of csv's for today into a text file. my $One_day = 86400; foreach my $list (@dir){ my $diff = time()-stat("$dirname/$list")->mtime; if( $One_day > $diff){ open FILE, ">>CPD_Files.txt" or die "Not able to open f +ile $!"; print FILE "$list\n"; } } closedir DIR; close FILE; # This is the code for getting the lines from the .csv's that I need #!/usr/bin/perl use strict; use warnings; use Text::CSV_XS; my $Finput = "cpd_link_ABC_cpddrops_50_300300000.csv"; my $Foutput = "data0426-2.csv"; open my $FH, "<", $Finput; open my $out, ">", $Foutput; my $csv = Text::CSV_XS->new({binary => 1, eol => $/ }); while(my $row = $csv->getline($FH)) { my @fields = @$row; if ($fields[2] eq "DROPPED-10" || $fields[2] eq "CALL_START" | +| $fields[2] eq "CALL_END") { $csv->print($out, $row); } } close $FH; if (not $csv->eof){ $csv->error_diag(); }
Extract the number of the species for txt file
1 direct reply — Read more / Contribute
by fan li
on Apr 27, 2016 at 10:24
    Hi everyone

    I am new to Perl. I want to get the specific information from a txt file by Perl. The following is description of the text file and what I want to get.


    C2H4 H2O3 C160H33O (1)

    1 2 5 (2)

    C2H4 H2O3 O4 (3)

    2 1 3 (4)

    C452H576O4 C2H4 (5)

    1 1 (6)


    The content of txt file is listed above. The name of the txt file is species.txt. There are two kinds of lines. One of the lines (labeled as (1) (3) (5)) is the chemical species and another one (labeled as (2) (4) (6)) is the number of the corresponding chemical species. And the chemical species and the numbers are not vertical alignment. And the chemical species are different from line to line. I want to get the number of the chemical species and output it into an Excel spreadsheet. Take the C2H4 as an example, the output should like this: C2H4




    How can I do that by Perl? Thanks for your help Fan Li

Set a screenshot from Selenium package in a variable
1 direct reply — Read more / Contribute
by Chaoui05
on Apr 27, 2016 at 09:30
    Hello Monks !! I am beginner and it's a real easy question. My issue is : I would like to get in a variable this path ($driver->capture_screenshot("D:/dev/drivers/snap-$browser.png"); ) to not have to write  D:/dev/drivers every time I tried to do this :
    my $path; $path->capture_screenshot{}
    And    $driver->capture_screenshot($path =>"snap-$browser.png");

    Many Thanks !!

Comparing Lines within a Word List
9 direct replies — Read more / Contribute
by dominick_t
on Apr 26, 2016 at 15:54
    Hello all-- New to Perl, new to this forum. Many thanks in advance for reading and offering help. I have a background in mathematics and have done a bit of programming, mostly for specific tasks that lead me to learn just enough of a language to achieve them. So I wouldn't call myself thoroughly conversant in any language. I am, however, interested in learning Perl more deeply, as I have some long-term projects that will require managing and searching through word lists in creative ways. I've been reading the O'Reilly book Learning Perl, but I have a specific problem that I need to solve somewhat urgently, and I'm afraid I haven't learned enough Perl yet to even attempt some code that could do it. So, here's the problem: I have a long list of text strings saved in a .txt file. What I am interested in are pairs of words that are exactly the same, except in one position . . . in particular, where one word has, say, an R, the other word has, say, an S. So if the word list was a standard dictionary and I ran the code on it, the output would include the pairs RAT and SAT, also RATE and SATE, also BARE and BASE, also BARR and BARS. This strikes me as something that should be possible using regular expressions in a Perl script. Am I right about that? If so, and if it's pretty easy for an expert to write some code that will do this, I would be much obliged, not just because I need a speedy solution to this question due to a deadline, but also because it will give me a great piece of example code to help me in getting my hands dirty learning Perl. All best-- Dominick
Perl sort
2 direct replies — Read more / Contribute
by xesecre
on Apr 26, 2016 at 10:25

    I have a question for the Wise Perl Monks, thanks in advance. I am using map and sort to sort by 2 columns. The trouble I am having is, it does sort the first column but it will not sort by any other column when I change the number. The list has numbers to sort. This is delimited by tab. What am I doing wrong?

    my @sorted = map {$_->[0]} sort { $a->[0] <=> $b->[0] || sort { $a->[1] <=> $b->[1] } map {chomp;[$_,split(/\t/)]} <FILE>; print OUT "$_\n" for @sorted;
Data Structure confusion...
4 direct replies — Read more / Contribute
by Spoon71
on Apr 26, 2016 at 09:30

    I'm trying to use a Perl module (Opsview::REST) it wants to use a data structure that looks like below. I'm properly confused as to what this is hash of hashes or whatever...

    'hostattributes' => [ { 'value' => 'some value +1', 'name' => 'URL', 'arg2' => undef, 'arg4' => undef, 'arg1' => ' +', 'arg3' => undef }, { 'arg3' => undef, 'arg1' => ' +m', 'name' => 'URL', 'arg4' => undef, 'arg2' => undef, 'value' => 'some value + 2' } ],

    I need to create it programatically as I need to read and parse data to create multiple blocks (which is no problem) then once created I need to pass it into the Opsview::Rest piece as below

    my $host = $ops->create_or_update_host( ip => '', name => "Name", hostgroup => { name => 'RDG - Prod Services' }, hosttemplates => [ { 'ref' => '/rest/config/hosttemplate/94 +', 'name' => 'AA-RDG-Pseudo-services' } ], hostattributes => PASS HERE, notification_period => { name => 'RDG-24x7-Minus-Bounce' } );

    I'm an occasional Perl programmer so this may be simple to some but I'm bloody confused, any help welcome

Net::SFTP::Foreign Transferred Bytes
1 direct reply — Read more / Contribute
by yulivee07
on Apr 26, 2016 at 09:24
    Hi fellow Perlmonks! I am currently having fun with Net::SFTP::Foreign. I am modifying a deamon which monitors a directory and automatically uploads files via sftp to a server. If there are multiple files, the deamon forks a child process for every file and transfers them in parallel.
    Now I want to do some better error handling. Wenn a transfer aborts, I want to print the number of bytes which were transferred. I can quite get this to STDOUT with the "more => -v" option.
    my $sftp = Net::SFTP::Foreign->new(host =>$host, user => $user, key_pa +th => [$privkey, $pubkey] , more => '-v'); [... debug output ...] Transferred: sent 32700048, received 60544 bytes, in 1.6 seconds Bytes per second: sent 20997978.1, received 38877.7 [... more debug output ..]
    My first approach was, to grep that output for the "Transferred" line. While this does work, that seems a bit overkill.
    I also tried utilizing the callback function of sftp->put like this:
    my $BYTES = 0; $sftp->put( "testfile", "testfile", cleanup => 1, callback => sub { my ( $sftp, $data, $offset, $size ) = @_; print $offset ." of ". $size ." bytes copied\n"; last_bytes($offset); + } ); print "\nTransferred $BYTES bytes\n"; + sub last_bytes { my ($bytes) = @_; $BYTES = $bytes; }

    However this is giving me a hard time, as I would have to track a variable per child I fork.

    In contrast, WWW::Curl has a method for getting the number of transferred bytes:

    $curl->getinfo( CURLINFO_SIZE_UPLOAD );
    I hope I am not missing something from the documentation for getting the transferred bytes from Net::SFTP::Forerign.... Any Ideas? I get the feeling I am nearly there with the callback-solution...

    Kind regards,
Scalable application with perl
5 direct replies — Read more / Contribute
by jasz
on Apr 26, 2016 at 08:49

    I am writing a new web application with a traffic of around 6k to 12k users connected for around 1.5 to 2 hrs. It is kind of an online examination. Can any one tell me

    what r the perl code changes to be made for such huge scalability ?

    what r the server side changes ?

    what r the database side changes (as the basic system has non partitioned table, single user etc) ?

    alternatives of backend languages for the requirement ?

HTML::Restrict works on the command line, but not the web server
1 direct reply — Read more / Contribute
by Zimtobi
on Apr 26, 2016 at 07:47

    Hello all! I just registered here because I don't find any solution to my PERL problem.

    So I want to strip certain tags from HTML in my PERL based Content Management System called Imperia.

    I installed HTML::Restrict on the server. It works just fine in a little PERL test program I wrote:

    #! /usr/local/bin/perl use strict; use HTML::Restrict; my $value = qq|<html> <head> <title>Dies ist der Titel</title> </head> <body> <p>Hier kommt der Inhalt</p> </body> </html> |; my $hr = HTML::Restrict->new(); my $value = $hr->process($value); print "Ergebnis: ".$value."\n\n";

    So now I want to use the module in my CMS. There is an interface called "transform". So I wrote this transform plugin:

    #! /bin/false # $Id:,v 2009/03/26 11:15:04 guido Exp $ # vim: set autoindent shiftwidth=4 tabstop=8: # Imperia AG is the sole owner and producer of its software "Imperia". + For # our software license and copyright information please refer to: Lice +nse.txt # Copyright (C) 1995-2012 Imperia AG. All rights reserved. package Dynamic::Transform::zim_iwe_filtern; use strict; use warnings; use HTML::Restrict; use Carp; sub new { my ($proto, $config) = @_; my $class = ref($proto) || $proto; bless {}, $class; } sub transform { my ($self, $metainfo) = @_; ## fetch all variable names my @keylist = sort $metainfo->keys(); my $count = 0; foreach my $key (@keylist) { ## only change certian variables next unless ( $key =~ m/^eingabe_/ or $key =~ m/^ff_confirm_/ or $key =~ m/^ff_successful_/ or $key =~ m/^map_point/ or $key =~ m/^map_text_/ or $key =~ m/^map_transcript_/ or $key =~ m/^tube_text_/ ); ## test value my $value = qq|<html> <head> <title>Dies ist der Titel</title> </head> <body> <p>Hier kommt der Inhalt</p> </body> </html> |; my $hr = HTML::Restrict->new() or die "Error at HTML::Restrict->ne +w: $!"; $value = $hr->process($value) or die "Error at process: $!"; $metainfo->setValues($key."_DEBUG", $value); } } 1;

    But in this environment the command $value = $hr->process($value) won't work. The result on the web interface of the cms is as follows: "Error at process: at /cms/ews-2000/site/modules/core/Dynamic/Transform/ line 55, <DEFAULTDATEI> line 102."

    This means that something goes wrong but the error variable $! isn't filled. The httpd error log shows no error either.

    I suspect that the module isn't fit to be used inside a package or I just invoke it wrong.

    Can anyone help me?

    Kind regards,
    Tobias from Germany

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 exploiting the Monastery: (13)
    As of 2016-04-29 14:14 GMT
    Find Nodes?
      Voting Booth?
      :nehw tseb si esrever ni gnitirW

      Results (441 votes). Check out past polls.