Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

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
Splitting a long row with multiple delimiters.
1 direct reply — Read more / Contribute
by dipit
on Jan 19, 2018 at 07:50

    eab12345 id=00000 pgrp=abcdefgh groups=abcdefgh home=/home/eab12345 shell=/usr/bin/ksh gecos=AB/C/Y0000/ABC/XYZ RTYUI, LMNOP *CONTRACTOR* (AS 00000) auditclasses=general,files,TCPIP login=true su=true rlogin=true daemon=true admin=false sugroups=ALL admgroups= tpath=nosak ttys=ALL expires=0 auth1=SYSTEM auth2=NONE umask=00 registry=AD SYSTEM=AD logintimes= loginretries=5 pwdwarntime=5 account_locked=false minage=0 maxage=13 maxexpired=0 minalpha=1 minother=1 mindiff=1 maxrepeats=2 minlen=8 histexpire=13 histsize=8 pwdchecks= dictionlist=/abc/def/ghi/jkl default_roles= fsize=-1 cpu=-1 data=-1 stack=65536 core=000000 rss=65536 nofiles=2000 time_last_login=1512632113 time_last_unsuccessful_login=1505304923 tty_last_login=ssh tty_last_unsuccessful_login=ssh host_last_login= host_last_unsuccessful_login= unsuccessful_login_count=0 roles=

    The above is a single row and i want to split values on the basis of <whitespaces>. Suppose the first key : eab12345 has null value but ended with white space. Similarly id=00000 ended with <whitespace>. But Gecos field contain spaces in between its values and if i split, i lose its whole value, For EX: gecos=AB/C/Y0000/ABC/XYZ RTYUI, LMNOP *CONTRACTOR* (AS 00000) contain <whitespaces> in its values. I cannot split using white spaces or else its value got merged with some other value. IS there any way i can have all the "key=values" in my array?(Doesn't matter values can be null or anything, in case its null there will be a whitespace, EX: admgroups= ) please help guys!

Data extraction with specific keywords
5 direct replies — Read more / Contribute
by neeraj_kr
on Jan 19, 2018 at 01:31

    I am trying to write a Perl code to extract specific keywords from a large data file. I have created an array where those specific keywords were stored. I was trying to read that large file line by line and extract matching keywords and want to store them in a new file. I am pasting my code here as it's not working properly. Help will be appreciated. Thank you.

    $a=`head -1 $ARGV[0]`; @arr=split(/\t/,$a); $col=$#arr; $c=0; @arr1 = ("91:", "86:", "184:", "430:", "391:", "254:", "121:", "192:", + "404:", "12:", "87:", "638:", "417:", "129:", "549:", "548:", "122:" +, "443:", "378:", "365:", "665:", "148:", "185:", "88:", "629:", "6 +37:", "149:", "625:", "635:", "627:", "650:", "468:", "92:", "618:", +"212:", "85:", "628:", "171:", "649:", "15:", "61:", "169:", "104:", +"202:", "523:", "60:", "672:", "291:", "658:", "59:", "547:", "491:", + "234:", "411:", "620:", "581:", "414:", "14:", "412:", "416:", "345: +", "626:", "457:", "72:", "384:", "371:", "9:", "580:", "436:", "356: +", "385:", "58:", "669:", "388:", "386:", "390:", "636:", "619:", "16 +:", "413:", "17:", "524:", "579:", "624:", "90:", "471:", "410:", "55 +1:", "289:", "387:", "531:", "64:", "166:", "211:", "467:", "415:", " +232:", "550:", "362:", "375:", "401:", "359:", "372:", "398:", "360:" +, "364:", "399:", "403:", "373:", "377:", "18:", "118:", "585:", "427 +:", "424:", "586:", "469:", "425:", "429:", "13:", "423:", "500:", "6 +2:", "109:", "19:", "539:", "499:", "532:", "400:", "63:", "361:", "3 +74:", "73:", "449:", "175:", "426:", "89:", "507:", "397:", "389:", " +582:", "475:", "20:", "22:", "541:", "492:", "503:", "555:", "595:", +"596:", "450:", "23:", "611:", "509:", "3:", "485:", "24:", "438:", " +442:", "440:", "484:", "117:", "32:", "437:", "31:", "663:", "339:", +"535:", "21:", "470:", "439:", "525:", "172:", "40:", "65:", "487:", +"50:", "517:", "597:", "545:", "516:", "402:", "347:", "614:", "540:" +, "613:", "346:", "67:", "363:", "583:", "376:", "428:", "71:", "615: +", "332:", "271:", "5:", "508:", "74:"); #print "$m\n"; print $arr[2],"\n"; for($i=1;$i<=$#arr+1;$i++) { foreach $ar(@arr1) { if ($arr[$i] == $ar) { $c[$j]=$i; $j++; # print $j; } #print $arr[1],"\n"; } } open(fh,"$ARGV[0]"); while(<fh>) { chomp $_; @arr2=split(/\,/,$_); foreach $ar(@c) { # print $arr2[$ar],"\t"; } #print "\n"; } close(fh);
substitution with regex
3 direct replies — Read more / Contribute
by drose2211
on Jan 18, 2018 at 20:03

    I am attempting to use regex on a text file that will match two numbers that represent temperature in Celsius. I attempted to put the numbers in two separate capture groups and then put them inside a formula to convert to Fahrenheit. I would then set two variables equal to two separate formulas with each using one of the capture groups. The point of this is to take a line like this:

    KSMO 181551Z 00000KT 10SM CLR 14/08 A3009 RMK AO2 SLP189 T01440083

    and take the "14/08" to convert it to Fahrenheit and substitute it back into the line. When I run my code I receive these errors:

    Odd number of elements in anonymous hash at line 11.

    Use of uninitialized value $1 in anonymous hash ({}) at line 11.

    Odd number of elements in anonymous hash at line 12.

    Use of uninitialized value $2 in anonymous hash ({}) at line 12.

    readline() on closed filehandle IN at line 13.

    I am wondering what I am missing. Is it an issue with my regex or somewhere else? Any help would be appreciated.

    #usr/bin/perl use strict; use warnings; open IN,'<',"part2.txt"; open OUT,'>',"airport_fahrenheit.txt"; my $x; my $fahrenheit1 = (9 *{$1}/5) + 32; my $fahrenheit2 = (9 *{$2}/5) + 32; foreach $x (<IN>){ ( $x =~ s/(\d\d)\/(\d\d)/$fahrenheit1\/$fahrenheit2/g ); print OUT "$x"; } close IN; close OUT;
regex is not working as I intended
5 direct replies — Read more / Contribute
by fireblood
on Jan 18, 2018 at 17:20
    Dear Monks and fellow followers,

    I am unable to understand why my regex is not working the way I intended. I'm trying to write a regex that recognizes when a parameter value is enclosed in single or double quotes and pulls out the value that lies between the quotes, or when the value is not quoted it simply returns the value. Here is my code:

    use strict; my $regex = qr / # start of regex ( # start of capturing alternation (?<=\') # positive lookbehind to a single quote ( # start of capture buffer 2 .*? # the value between the single quotes ) # end of capture buffer 2 (?>\') # positive lookahead to a single quote | # or (?<=\") # positive lookbehind to a double quote ( # start of capture buffer 3 .*? # the value between the double quotes ) # end of capture buffer 3 (?>\") # positive lookahead to a double quote | # or ( # start of capture buffer 4 .* # any unquoted value ) # end of capture buffer 4 ) # end of capturing alternation /x # end of regex ; &do_test (\"Now is the time"); # test with unquoted value &do_test (\"'Now is the time'"); # test with single quoted value &do_test (\'"Now is the time"'); # test with double quoted value sub do_test { print "\n"; if (${$_[0]} =~ /$regex/) { print "\$1 is $1.\n"; print "\$2 is $2.\n"; print "\$3 is $3.\n"; print "\$4 is $4.\n"; } else { print "No match.\n"; } }
    When I run this, I get:

    $1 is Now is the time. $2 is . $3 is . $4 is Now is the time. $1 is 'Now is the time'. $2 is . $3 is . $4 is 'Now is the time'. $1 is "Now is the time". $2 is . $3 is . $4 is "Now is the time".

    Why are the first two alternatives not capturing quoted test strings?
apply_all_roles method clobbering MooseX::Log::Log4perl
1 direct reply — Read more / Contribute
by nysus
on Jan 18, 2018 at 10:16

    I have the following:

    { package MyApp; use Moose; use Moose::Util qw( apply_all_roles ); with 'MooseX::Log::Log4perl'; sub BUILD { my $s = shift; # apply_all_roles($s, 'BarCollector'); # if you uncomment this li +ne, logging doesn't work anymore } sub print_something { my $self = shift; $self->log->info('This does not print when apply_all_roles is used +.'); } } { package BarCollector; use Moose::Role # does nothing } #! /usr/bin/env perl use File::HomeDir; use Log::Log4perl; BEGIN { Log::Log4perl->init_once(File::HomeDir->my_home . '/test.cfg') + }; use MyApp; my $app = MyApp->new(); $app->print_something; __END__ # test.cfg config file: log4perl.logger.MyApp=TRACE, LOG log4perl.appender.LOG=Log::Log4perl::Appender::ScreenColoredLevels log4perl.appender.LOG.layout=PatternLayout log4perl.appender.LOG.layout.ConversionPattern=%c - %m%n

    As noted in the comment, when the line that contains apply_all_roles is uncommented, log messages no longer work. There are no errors.

    Update: One other clue is that when I change the first line of the config file to: log4perl.rootLogger=TRACE, LOG

    I get output, though the category looks something like this: Moose.Meta.Class.__ANON__.SERIAL.1

    Any workaround to this?

    Update 2: Possible workaround?

    I discovered if I slap $s->log->trace('print this'); before the apply_all_roles method is called, everything works as expected. Is there a better way?

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate Priest";
    $nysus = $PM . ' ' . $MCF;
    Click here if you love Perl Monks

Getting attachments from request in perl
2 direct replies — Read more / Contribute
by Stetec
on Jan 18, 2018 at 09:36
    I want to use a form to submit fields of email so server can send it. I use Perl and Mason to handle this. I want a user to be able to add multiple attachments, however I am encountering a problem that I can not solve. This is my code simplified as much as possible and with added check for the attachments. ( After submit I want to stay at the same page, that is why there is a hidden check-box and condition in Init section, so that it does nothing when I visit the page for the first time. )
    <!DOCTYPE html> <html> %foreach (@messages) { <div class="alert"> <% $_ | h %> </div> %} <body> <form action="/Tools/SendEmail.html" name="form" enctype="multi +part/form-data" method=post> <input type="checkbox" id="submited_chck" name="submited" +checked hidden> <input type="file" name="attached_files" id="file_upload_b +tn" multiple> <input type="submit" value="Submit"> </form> </body> </html> <%args> @messages => () $submited => '' </%args> <%init> use strict; use warnings; use CGI; if($submited eq 'on') { my $req = new CGI; my @attachments = $req->param('attached_files'); unless (@attachments) { push @messages, "Attachments do not exist"; } } </%init>
    The problem is that if I do any request before submit and add any number of attachments it does not get the attachment from request and the error message is pushed into array and displayed. It does not push the error message only if I restart apache service and submit the form right after it. Any ideas what can cause this? I posted this also on stack overflow but no-one is able to help. Here is a link to it
Problem with SOAP call using SOAP::Lite and wsdl
1 direct reply — Read more / Contribute
by Anonymous Monk
on Jan 18, 2018 at 04:15

    I'm trying to do a SOAP call to

    My code as follows :

    use SOAP::Lite; my $client = SOAP::Lite->new; $client = $client->service( " +d.asmx?wsdl" ); my $soapResp = $client->call( "ConvertSpeed", 100, "kilometersPerhour" +, "milesPerhour" ); if ( $soapResp->fault ) { print $soapResp->faultstring; } else { print $soapResp->result; }

    This gives me the following error :

    A service address has not been specified either by using SOAP::Lite->proxy() or a service description)

    As far as I understand it the service address is obtained from the WSDL. I did however try using
    $client->proxy(""), but then I got the following error :

    Server did not recognize the value of HTTP Header SOAPAction: #ConvertSpeed

    Since the WSDL is supposed to handle the service address I removed the $client->proxy() bit and tried
    other stuff. I have been struggling with this for 2 days now so I can't recall everything I tried, but
    I did reduce method chaining a lot from my initial code to what I posted above. I also tried using
    $client->ConvertSpeed(100, "kilometersPerhour", "milesPerhour") directly as I have seen it done this way
    elsewhere, but it seems to not return anything.

    This is running on Perl 5.10 and version 0.714 of SOAP::Lite.
    I have also tested on Perl 5.22.1 and version 1.19.

    I have also confirmed that this SOAP call works in other languages.

3 direct replies — Read more / Contribute
by BillB
on Jan 17, 2018 at 16:48
    I installed the Perl build from active state on my 64 bit windows 7 machine. However I have to be able to connect to an Oracle 8I database using a 10g client. The 10g client can connect to the database with no problems, but when I try to use DBI it says that that version is no longer supported. I looked up the newest version that will support my database and it is version 1.20 I was able to download the 1.20 version for DBD::Oracle from CPAN but following the instructions I can't get it to replace the version used by my 64 bit version of Perl. Does anyone know how to do this. It is very frustrating. By the way version 1.20 will talk to all versions of the database, it just doesn't support the newest bells and whistles.
Memory utilization and hashes
9 direct replies — Read more / Contribute
by bfdi533
on Jan 17, 2018 at 15:53

    I have some code which reads from a file (sometimes 100+ GB) and has to combine rows to create a consolidated output. I used to process the entire file into a hash and then dump the hash at the end of the program.

    The problem with that was, of course, with the very large files, the hash would grow humongous and the program would consume all memory in the system causing it to crash.

    So, trying to solve this problem, I changed the code to output the data as it went, doing my best to make sure that I got all of the row data for consolidation and the did a delete on the hash, thinking I was clearing up memory. But, this does not appear to be the case. Example code:

    my $l; my @vals; my $json; while (<>) { $l = $_; chomp $l; @vals = split /;/, $l; if ($vals[0] =~ /Query/) { $pairs{$vals[1]}{$vals[2]} = $vals[3]; } elsif {$vals[0] =~ /Answer/) { $pairs{$vals[1}{$vals[2]} = $vals[3]; $json = encode_json $pairs{$vals[1]}; print $json."\n"; delete $pairs{$vals[1]}; } }
    Example data:
    Query;1;host; Answer;1;ip; Query;2;host; Query;3;host; Answer;2;ip; Answer;3;ip;

    Does delete actually remove the storage from the hash?

    Does the memory the hash is using actually get reduced after delete?

    Is there a better way to do this?

    Code updated above per the first reply.

service status query with wrong status
3 direct replies — Read more / Contribute
by ytjPerl
on Jan 17, 2018 at 09:43
    I have a perl script to query the status of my windows server 2012 R2 services. I am unable to get the correct status via running the script. the service status is 'running', but I got 'continue_pending'. I am still trying to figure out if the status I stat in @state_name are correct.
    use Win32::Service qw'GetStatus'; use strict; use POSIX; my @state_name = qw( Stopped START_PENDING STOP_PENDING Running CONTINUE_PENDING PAUSE_PENDING PAUSED ERROR ); my $filename = 'D:/log_script/recycle/StartupSvcList.txt'; open FILE, '<', $filename or die "cannot open"; while (<FILE>){ GetStatus("", $servicename, \%status); my $state_no = $status{'CurrentState'}; printf MYFILE " ServiceStatus: %s %s %s \n", "", $servicename, $st +ate_name[$state_no]; } close(MYFILE);


    Discipulus added a missing closing code tag

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
    [erix]: my "Jeschwätz von jestern" = "Geschwätz von gestern" = "my babbling of yesterday"
    [marto]: thanks erix

    How do I use this? | Other CB clients
    Other Users?
    Others lurking in the Monastery: (13)
    As of 2018-01-19 13:47 GMT
    Find Nodes?
      Voting Booth?
      How did you see in the new year?

      Results (218 votes). Check out past polls.