Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

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
Can't copy file
2 direct replies — Read more / Contribute
by novice2015
on Mar 30, 2015 at 15:37

    I am a total beginner and have a script like this: It runs fine the only problem is it does not copy the data in output1.txt to output3.txt. It creates output3.txt but does not copy the data. Why?

    #!/usr/bin/perl my $server = `uname -n`; print $server; chomp $server; # Display all the files in /tmp directory. $dir = "/usr/ent/newdir/db/sign/*"; my @files = </usr/ent/newdir/db/sign/*files*>; open(my $outfh, '>', '/tmp/output1.txt') or die "cannot open file"; foreach $LINE (@files ){ print $outfh $LINE; close FH; } use File::Copy; {$oldlocation = "/tmp/output1.txt"; $newlocation = "/tmp/output3.txt"; copy($oldlocation, $newlocation); }
starters querry
4 direct replies — Read more / Contribute
by Mahadevk
on Mar 30, 2015 at 13:49
    Hello, I am starting to learn perl. when i go to run and type perl it opens but when i type the basic program $a=2; $b=$a + $a; print $b ; and then press enter i dont get any output.i thought i would get 4 as output. i want to know what i am doing wrong.need some help just to start. i tried going to perl critic but it gives error message on the first line.error message is 'code before strictures are enabled' some one please help.
Quick question: ForkManager
No replies — Read more | Post response
by pimperator
on Mar 30, 2015 at 12:53

    Hello Monks

    Quick question, I'm submitting a PBS job to the cluster that has a perl script with Parallel::ForkManager. In this script I want to fork off 32 processes for each file in an array I'm looping through.

    When I ask for  #PBS -l nodes=4:ppn=8

    does that mean that perl will fork off each process to run on each processor? Or do I need use threads;

Passing values to a Perl script from PHP
1 direct reply — Read more / Contribute
by Yary
on Mar 30, 2015 at 11:54
    I am posting this question & my response, which came into the CPAN::Testers list. This seems like a better place and I am directing the original poster to this node. Thanks to the fellow monks who helped this fellow out on the mailing list before now.

    On Sun, Mar 29, 2015 at 11:26 PM, Uday Shankar Kintali wrote:

    > Looking if I can pass on the user selected values ( in php form) to the perl script.

    Since you are calling the script using "system", there are a few general ways of getting the caller (PHP in this case) parameters to the callee (Perl):
    1. Environment variables. If you can set them in PHP before calling system, you ought to be able to retrieve them in Perl using $ENV{Env_var_name}, replacing "Env_var_name" with whatever environment variable you want to read. This seems the safest to me for simple use.
    2. Command-line arguments. If in PHP you run "system ' arg0 arg1 arg2'", then Perl will have the arguments in @ARGV. $ARGV[0] eq 'arg0' && $ARGV[1] eq 'arg1', etc. Be careful if any of your arguments have spaces or shell-special characters like quotes, pipes- unless PHP has a form of "system" that takes care of those for you. Perl's "system" will do so, if you pass "system" a list or array instead of a string/scalar, but I don't know about PHP, and you are calling "system" from PHP.
    3. Pipe the data into Perl. A quick scan of PHP documentation says to do something like this:
      $handle = popen('','w'); fwrite($handle,"here is some input\n"); fwrite($handle,"more input\n"); # etc.... pclose($handle);
      and then in Perl you can read it like:
      while (<STDIN>) { # Do something with the line we just read }
    4. Some mutually agreed upon data store: a file, a database, shared-memory cache, etc. Need to be careful about handing the right data to the right process, if there's any chance of there being multi-process, and also careful about data lifetime- cleaning up old values, but not too soon. I won't go into the details here.
HTML Parser strange Null Character in data
3 direct replies — Read more / Contribute
by caind
on Mar 30, 2015 at 10:36
    Iím stuck, Iíve been trying to clean up my mistakes and I have a few I just canít seem to figure out. Maybe Iím too close, but I decided an extra set of eyes may be just what I need.

    I have written a script that will monitor the output of a database that is pushed to a website. Iím just scraping the site and then parsing the table. This is where I seem to run into a problem. First the site can take a little while to respond every now and then. This will shut down the script; I may have the solved with the goto statement. But, if there is a better way, Iím always willing to learn. Next either the data I get or the way I parse the table is putting a (? Space, Null, non-printable characterÖ..something It looks like the degree symbol followed by a middle dot į∙ ?) in front of the incident number only. Every now and then another column will have this happen and shutdown the script.. Iíve tried everything I can think of to the point of pulling out my hair. Now Iím just taking shots in the dark hoping something will hit. This will create a problem with naming and saving and recalling the file.

    BTW Iím not a developer; Iím just dangerous with a little bit of knowledge of Perl. So that being said I have a lot of gaps in my knowledge but Iím willing to learn.

    ### Script trimmed down ##### GET: getstore (' +=50&Sort_By=INC_Incident.IncidentNumber&Sort_Type=ASC&displayColumnLi +st=1,2,3,4,5,6,7', 'tempincid.html')or goto GET; my $html = 'tempincid.html'; my $te = HTML::TableExtract->new( headers => [("", "Incident # ", "Dispatch Time", "Incident Type", "Address", "Apt. #", "Postal Code", "Unit Dispatched")] ); $te->parse_file($html); $config{'header'} =<<"EOF"; <html> <head> <meta http-equiv="Content-Type" content="text/html"><title>ESSI | Onli +ne Home</title> <meta http-equiv="cache-control" content="no-cache" /> <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> <META HTTP-EQUIV="REFRESH" CONTENT="15"> <link href="/Page_style/page.css" rel="stylesheet" type="text/css"></h +ead> <body> EOF my $file = "tempincid.html"; my $date = POSIX::strftime( "%c", localtime( ( stat $file )[9] ) ); my $row = @{$te->rows}; print $config{'header'}; print "<TABLE align=\"center\" border=\"1\" cellpadding=\"2\" cellspac +ing=\"0\" width=\"100%\" style=\"font-size: 12px;\">"; foreach my $ts ($te->tables) { foreach my $row ($ts->rows) { print "<tr><td> ", join(' </td><td> ', @$row), "\n"; ##### +####Every now and then the cell prints a stream of errors. I'm Guessi +ng it is that character I can identify #### print "</td></tr>" , "\n"; } } print "</Table>", "Dispatcher data last read $date", "</body></html>"; my $numColumns = @{$te->rows->[0]}; my $numRows = @{$te->rows}; for my $rowIndex ( 0..$numRows-3 ) { for my $columnIndex ( 0..$numColumns-1 ) { my $cellvalue = $te->rows->[$rowIndex][7]; foreach ($cellvalue) {chomp;} { $cellvalue=uc($cellvalue); if (($cellvalue =~ /BT/) || ($cellvalue =~ /FB/)) { my $path = "C:/incidentnum/"; my $cellmatch = $te->rows->[$rowIndex][$columnIndex]; #********************************************************************* +*********************############################## #---------------Read each cell and as they are opened trim all whitesp +aces from the left and right side-----------------# #------There is still some non-viewable (Null space, non-printable cha +racter to the left of the incident number.--------# ###################################################################### +################################################### my $cell1=$te->rows->[$rowIndex][1]; $cell1 =~ s/^\s+|\s+//g; $cell1 =~ s/^\s+|\s(?=\s)|\s+$//g; my $cell2=$te->rows->[$rowIndex][2]; $cell2 =~ s/^\s+|\s+$//g; my $cell3=$te->rows->[$rowIndex][3]; $cell3 =~ s/^\s+|\s+$//g; my $cell4=$te->rows->[$rowIndex][4]; $cell4 =~ s/^\s+|\s+$//g; my $cell5=$te->rows->[$rowIndex][5]; $cell5 =~ s/^\s+|\s+$//g; my $cell7=$te->rows->[$rowIndex][7]; $cell7 =~ s/^\s+|\s+$//g; my $row="$cell1, $cell2, $cell3, $cell4, $cell5, $cell7"; my $filename = $cell1."."."txt"; $filename =~ s/^\s+|\s+$//g; #$filename =~ s/^S+|\S+$//g; $path =~ s/^\s+|\s+$//g; $path =~ s/^\s+|\s(?=\s)|\s+$//g; my $full ="$path$filename"; open (FILE, '>', $filename) or die("Couldn't open $filename"); print FILE "$row"; close(FILE)or die $!; my $powershell = 'C:\Windows\System32\WindowsPowerShell\v1.0\p +owershell.exe'; my $mboxScript = 'C:\inetpub\cgi-bin\EmailAlert.ps1'; my $result = `$powershell -command "$mboxScript"`; print "$powershell\n"; print "$mboxScript\n"; goto EEND; } } } } EEND: exit 0;
Substituting with match containing newline and space characters
2 direct replies — Read more / Contribute
by MorayJ
on Mar 30, 2015 at 08:19


    I'm trying to do a substitution in a file

    I am trying to match:

    <input type="checkbox" ng-model="[0]"

    I then want to switch it out so it says

    <input type="checkbox" ng-model="[0]" label="loan"

    I am trying the following code:

    while ($my_file =~ /(input type=\"checkbox\".*?(\w+)\[0\])/sg) { $my_file =~ s/$1/$1 label="$2"/s; };

    But, although the match works when I print it out ($1 prints the line I want to match), it doesn't work when I use it in the substitution.

    Even if I replace the substitution with a literal switch like

    s /$1/TEST/s;

    I think this is because the match($1) has a newline and some spaces in it

    If that's the case, how do I tell it to use exactly what's in the match in the substitution (and why doesn't it do that anyway)?

    Or have I probably made a mistake somewhere?

    Thanks for your help


Python dict to perl hash
8 direct replies — Read more / Contribute
by garg10may
on Mar 30, 2015 at 07:32
    Hi Monks, I want to convert a python dict to perl hash. Is there a better/easy way to do this than below.
    use Data::Dumper; sub rot13 { my $x = "'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g' +:'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', +'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', +'x':'k', 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', +'F':'S', 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', +'N':'A', 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', +'V':'I', 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'"; $x =~ s/['\s+]//g; my %hash = split /[:,]/, $x; print Dumper\%hash; } rot13();
Pattern matching: Lazy vs. greedy
5 direct replies — Read more / Contribute
by false_friend
on Mar 30, 2015 at 04:42

    Dear Monks,

    I am trying to do pattern matching, but canít get the results I am looking for. Here is a very reduced example of what I am trying to do:

    My search string is The quick brown fox jumps over the lazy dog, and I am trying to match the lazy dog, but my problem is that I only have limited information about the snipped that I am interested in; I only know the first word (the) and the last word (dog). I tried to accomplish this with a simple lazy regular expression:

    #!/usr/bin/perl -w use strict; my $string = "The quick brown fox jumps over the lazy dog"; $string =~ /(the .*? dog)/i; print "Match: '", $1, "'";

    But this gives me

    Match: 'The quick brown fox jumps over the lazy dog'

    instead of the desired

    Match: 'the lazy dog'

    Is there an elegant way of matching in the Ďlaziestí way (in the sense that a three-word match is lazier than matching the whole string)?

    Thank you for you help,


Module for Conditional Parsing
4 direct replies — Read more / Contribute
by mwb613
on Mar 30, 2015 at 03:16

    Hello, thanks for looking!

    I have been looking around CPAN for a module that might save me from starting from scratch. So far I haven't found what I'm looking for hopefully due to a failure to use the proper terminology or focusing on too narrow of a use case.

    I have some data in Redis that I'd like to be able to run SQL-style queries on. I'm not looking to invent a SQL wrapper for Redis but I do think it would be useful to have an ability to test values against ad hoc conditionals.

    I'd like to be able to pass a subroutine a conditional test and a value to test against it. For example the conditional could be a hash ref like this (say we're testing a zip code):

    my $conditional_test = { 'OR' => { 'condition1' => { 'value' => '10022' } 'condition2' => { 'value' => '96813' } 'condition3' => { 'value' => '55401' } } } if(my_condition_test_sub($conditional_test,$redis_handle->get('key'))) +{ #do something }

    Possible conditions could be (and, or, not...)

    Ideally we could nest these conditions as well which is why I'm looking for a parser that's already built. I did find a grammar parser that looked like it worked for natural language as well as some conditional parsers specific to specialized data (XML, lists) but nothing generalized.

    Has anyone come across this particular problem (not Redis queries but checking data against ad hoc value tests) before and found a good solution? It seems like a use case that might warrant a module.

    Thanks again for looking.

Duplicate File Finder script reporting multiples
2 direct replies — Read more / Contribute
by Anonymous Monk
on Mar 30, 2015 at 02:41

    Hi Monks

    Could someone please advise as to why the following code is reporting the same files a few times...

    #!/usr/bin/perl -w use strict; use File::Find; no warnings 'File::Find'; use Digest::MD5; local $| = 1; my $path = $ARGV[0]; #my $testpath = 'C:/Temp/'; print "Searching for duplicate files in $path\n"; #find(\&check_file, $testpath); find(\&check_file, $path); local $" = ""; my %files; my %md5; my $wasted = 0; my $size = 0; foreach my $size (sort {$b <=> $a} keys %files) { next unless @{$files{$size}} > 1; foreach my $file (@{$files{$size}}) { open(FILE, $file) or next; binmode(FILE); push @{$md5{Digest::MD5->new->addfile(*FILE)->hexdigest}},$file."\ +n"; } foreach my $hash (keys %md5) { next unless @{$md5{$hash}} > 1; print "\n@{$md5{$hash}}"; print "File size $size\n \n"; $wasted += $size * (@{$md5{$hash}} - 1); } } 1 while $wasted =~ s/^([-+]?\d+)(\d{3})/$1,$2/; print "\n$wasted bytes in duplicated files\n"; sub check_file { (my $fn = $File::Find::name) =~ tr#/#\\#; -f && push @{$files{(stat(_))[7]}}, $fn; }


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 avoiding work at the Monastery: (17)
    As of 2015-03-30 20:33 GMT
    Find Nodes?
      Voting Booth?

      When putting a smiley right before a closing parenthesis, do you:

      Results (659 votes), past polls