Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
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
In place search and replace with a hash
3 direct replies — Read more / Contribute
by hkates
on Dec 27, 2014 at 20:49

    I want to replace a set of strings across multiple files. Ideally, I want to change the files in place. I have a hash where the keys are the strings to find, and the values are the strings to replace them with.

    So something like s/$key/$hash{$key}/g. Below is my code to build the hash and to search files for the hash keys and replace them with the associated hash values. The errors are included at the end. I ensured that the hash is working, and I have tested that my regex is correct as well.

    open my $fh, '<', 'hash.txt' or die "Can't open file $!"; LINE: while (my $line = <$fh>) { my ($key, $value) = split /\s/, $line; next LINE if not $key; $hash{$key} = $value; chomp (%hash); } close $fh; @file_array =<*.txt> or die $!; foreach $file (@file_array) { open FH, "$file", or die $!; while (<FH>) { if (/(\S+):(\S+).*\n/) { s/$1/$hash{'$1'}_$2/g; } } close FH; }

    The s/foo/bar/g itself is not working (I tried s/$1/$2/g), and I have never done a find and replace in place before. I am getting two "use of uninitialized value" errors:

    Use of uninitialized value $hash{"$1"} in concatenation (.) or string at test_perl.pl line 29, <FH> line 5.

    Use of uninitialized value $2 in substitution iterator at test_perl.pl line 30, <FH> line 5.

    I get these errors once for every line in FH where the search pattern is found.

    Thanks for reading!

how to execute multiple Perl scripts
4 direct replies — Read more / Contribute
by vasuperl
on Dec 27, 2014 at 13:36

    I have a small doubt in Perl? can any one do your favour? I have 4 Perl scripts like step1.pl, step2.pl, step3.pl, step4.pl.. I want to execute those 4 scripts consecutively such that the master script should exit if there is any error in any of the script...for example if there is an error in step1.pl, then it should not execute step2.pl, it should exit from the script.. if any of you had any idea how to do this, please help me.. I am a beginner of Perl.. please do needful.

READ one line at a time
3 direct replies — Read more / Contribute
by wrkrbeee
on Dec 27, 2014 at 10:27

    Hello PerlMonks, Inherited a program that creates the "Out of Memory" error. Modified the code to read one line at a time rather than store the entire file in a variable (or so I thought). Program runs/works, but still encounters the "Out of Memory" error (obviously I failed). I suspect that the problem lies with a foreach statement at line 59. I'm thinking that the notion of reading all files into an array is unnecessary. Hence, lines 51-59 can be dropped. However, my dilemma now is how do I assign the filename to $file in lines 63 and 86? Apologize for such a trivial question to experienced users. Program is below. I am grateful for any insight you may have. Thanks!!

    #!/usr/bin/perl -w #use strict; # This program extracts data from an SEC filing, including chunks of t +ext use File::stat; #This program is going to obtain and extract the entire audit opinion +but you can #extract whatever text you are interested in by changing the regular e +xpressions for the start #and end strings below. #This program was written by Andy Leone, May 15 2007 and updated July + 25, 2008. #You are free to use this program for your own use. My only request i +s #that you make an acknowledgement in any research manuscripts that #benefit from the program. my $startstring='((^\s*?)((We\s*(have|were)\s*(audited\s*the\s*(Statem +ent\s*of\s*Financial\s*Condition|consolidated|accompanying|combined|b +alance\s*sheets)|(completed\s*|engaged\s*to\s*perform)\s*an\s*integra +ted\s*audit))|In\s*our\s*opinion,\s*the\s*(consolidated|accompanying) +))'; my $startstringhtm='(((We\s*(have|were)\s*(audited\s*the\s*(Statement\ +s*of\s*Financial\s*Condition|consolidated|accompanying|combined|balan +ce\s*sheets)|(completed\s*|engaged\s*to\s*perform)\s*an\s*integrated\ +s*audit))|In\s*our\s*opinion,\s*the\s*(consolidated|accompanying)))'; + #Specify the end of the text you are looking for. my $endstring='((^\s*)/s/|^\s*(Date:\s*)?(\d{1,2}\s*)?((January|Februa +ry|March|April|May|June|July|August|September|October|November|Decemb +er))\s*(\d{1,2},)?\s*\d{4}(\s*$|,\s{0,3}except|\s*/s|\s*s/|\d{1,2}))' +; my $endstringhtm='((>|^\s*)(/s/)?\s*(Date:\s*)?(\d{1,2}\s*)?(January|F +ebruary|March|April|May|June|July|August|September|October|November|D +ecember))\s*(&\w+?;\s*)?(\d{1,2},)?\s*\d{4}(\s*$|\s*[,\(]\s{0,3}excep +t|\s*with\s*respect\s*to\s*our\s*opinion|<\/P>|<BR>|\s{0,1}\<\/FONT\> +|\d{1,2})'; #Specify the directory containing the files that you want to read my $direct="E:\\Research\\SEC filings 10K and 10Q\\Data\\Filing Docs\\ +2008test"; my $outfile="E:\\Research\\SEC filings 10K and 10Q\\Data\\Header Data\ +\Data2008test.txt"; #If Windows "\\", if Mac "/"; my $slash='\\'; $outfiler=">$outfile"; open(OUTPUT, "$outfiler") || die "file for 2006 1: $!"; #The following two steps open the directory containing the files you p +lan to read #and then stores the name of each file in an array called @New1. opendir(DIR1,"$direct")||die "Can't open directory"; my @New1=readdir(DIR1); #We will now loop through each file. THe file names #have been stored in the array called @New1; foreach $file(@New1) { #This prevents me from reading the first two entries in a directory . +and ..; if ($file=~/^\./){next;} #Initialize the variable names. my $cik=-99; my $form_type=""; my $report_date=-99; my $file_date=-99; my $name=""; my $sic=-99; my $HTML=0; my $Audit_Opinion="Not Found"; my $Going_Concern=0; my $ao="Not Found"; my $tree="Empty"; my $data=""; #Open the file and put the file in variable called $data #$data will contain the entire filing { # this step removes the default end of line character (\n) # so the the entire file can be read in at once. local $/; #read the contents into data open (INPUT, "$direct$slash"."$file"); while ($data=<INPUT> ) { #The following steps obtain basic data from the filings if ($data=~m/<HTML>/i){$HTML=1;} if($data=~m/^\s*CENTRAL\s*INDEX\s*KEY:\s*(\d*)/m){$cik=$1;} if($data=~m/^\s*FORM\s*TYPE:\s*(.*$)/m){$form_type=$1;} if($data=~m/^\s*CONFORMED\s*PERIOD\s*OF\s*REPORT:\s*(\d*)/m){$report +_date=$1;} if($data=~m/^\s*FILED\s*AS\s*OF\s*DATE:\s*(\d*)/m){$file_date=$1;} if($data=~m/^\s*COMPANY\s*CONFORMED\s*NAME:\s*(.*$)/m){$name=$1;} if($data=~m/^\s*STANDARD\s*INDUSTRIAL\s*CLASSIFICATION:.*?\[(\d{4})/ +m){$sic=$1;} my $filesize = -s $direct . '/' . $file; my $sb = stat($direct . '/' . $file)->size; print OUTPUT "$cik,$form_type,$report_date,$file_date,$name,$sic,$file +size,$sb\n"; } close INPUT or die "cannot close $file: $!"; } }
Question on Regular Expression
5 direct replies — Read more / Contribute
by sjain
on Dec 26, 2014 at 19:07

    Hi everyone, I have a question related to regular expression and below are 2 code snippets. Can you please advise why they give diffferent output? What is wrong with code snippet 2 ?

    Code Snippet 1

    #!/usr/bin/perl use re qw(eval); my $pattern1; my $str1 = "RS"; $pattern1 = qr{(?<P_ROOTCODE>.*)(?{ push(@rc1, ${^MATCH}) })\K(?{ $p_r +ootcode = "@rc1" })(?<DAY1>[0-9])(?{ push(@rc2, ${^MATCH}) })(?<P_MON +_CODE>[A-Z])(?{ push(@rc3, ${^MATCH}) })$}; $str1 =~ m/$pattern1/; print "Value of p_rootcode in Pattern 1 is : $p_rootcode\n";

    Code Snippet 2

    #!/usr/bin/perl use re qw(eval); my $pattern2; my $str2 = "RS"; $pattern2 = qr{(?<P_ROOTCODE>.*)(?{ push(@rc1, ${^MATCH}) })\K(?{ $p_r +ootcode = "@rc1" })(?<DAY1>[0-9])(?{ push(@rc2, ${^MATCH}) })(?<P_MON +_CODE>[A-Z])(?{ push(@rc3, ${^MATCH}) })(?<P_NEW_MON_CODE>[A-Z])(?{ p +ush(@rc4, ${^MATCH}) })$}; $str2 =~ m/$pattern2/; print "Value of p_rootcode in Pattern 2 is : $p_rootcode\n";
displaying an email attachment from a hyperlink
1 direct reply — Read more / Contribute
by Anonymous Monk
on Dec 26, 2014 at 15:37
    Hi Monks,

    WARNING ====> Depending on the solution, this might be more of an html question than a Mime::Lite question, but either way, i'm confident that you monks will know what I'm doing wrong here. I have never been disappointed by this site.

    I am using Mime::Lite to email an html report which contains a hyperlink of text data. When a user clicks on the hyperlink, I want the text to be displayed in an appropriate OS application (in my case, it's Notepad). This seems simple enough, so I tried the following:

    ## this will not run and generate an html report my $html = <html content> my $msg = MIME::Lite->new( Subject => 'my html report', To => 'xxx@gmail.com', Type => 'text/html', Data => $html); $msg->attach( Type => 'text/plain', Path => '/var/tmp/data.txt' Disposition => 'attachment'
    I thought that referencing the attachment in an href like the following would do the trick
    <a href="./data.txt">
    but lo and behold, I have been fooled again! Strangely enough, I did this for image files with and it worked splendidly, so I'm not sure why it wouldn't work the same for plain text files. Anyone know what I'm doing wrong here?

    AS usual, thanks for taking the time to read my lengthy message.

    Best Regards, Michael

How to split big files with Perl ?
4 direct replies — Read more / Contribute
by zalezny
on Dec 26, 2014 at 12:20
    Hi Perl Gurus, does anybody knows how to split big files (for example: 10GB) to multiple small ones ? For example, I would like to take each big file in my backup folder and split for small peaces. For example 10GB file backup.dat needs to be splitted to :

    backup.dat.aa

    backup.dat.ab

    backup.dat.ac

    Is there any library in Perl for splitting files base on the size ? Or maybe some compress parameter to split automaticly files if they are bigger than size XX ? Thanks in advance for Your support ! Zalezny
SMS services
2 direct replies — Read more / Contribute
by jatuljain
on Dec 26, 2014 at 06:00

    I am new to SMPP module. I am looking for some script which can send a SMS from ESME --> SMSC. Though this we already have as "sendmessage.pl".

    My intention is to check SMSC server.

    What I need next is receive the same SMS sent to other ESME. In this case let say receive.pl. Basically setup would be like ESME (Subscriber 1) --> SMSC --> ESME(Subscriber 2) Can you please help me in this. I am able to send Submit_sm and get the response. But I am not getting how to forward the same to ESME receiver side ?

How to issue "Ctrl-y" to a network device
1 direct reply — Read more / Contribute
by sriram83.life
on Dec 26, 2014 at 01:59
    Hello Monks,

    I am executing commands on telecommunications 2G/3G network devices like GCS /MSS. On these elements, once a command is executed,i need to issue a "Ctrl-y" ( Contol y command) to exit from the previous prompt.But, I am not able to issue Ctrl-y to the device.This makes the device to wait until it times out and continue with other commands. This is delaying my script to execute and it is running for more than one day.I am able to enter into the router from which i can issue commands on to the device,but i am not able to "\cy" command on the device. Your help is much appreciated.

    Sriram

Method of child module called by parent
1 direct reply — Read more / Contribute
by gzartman
on Dec 25, 2014 at 23:51
    I'm somewhat new to perl OOP. I've been working on a perl module and found that it was getting a big unwieldy, so decided to spin off a few child classes to my main class to help organization and what not. I'd like to be able to call methods from the child class as if they were in the parent class (at least that's how I envisioned this working). Simplified example:
    package parentClass; use parentClass::childClass; sub new { my ($class, %params) = @_; my $self = {}; bless ($self, $class); return ($self); } 1; package parentClass::childClass; sub new { my ($class, %params) = @_; my $self = {}; bless ($self, $class); return ($self); } sub myMethod { return ('Yo I am one sweet method'); } Test Script utilizing these classes: use parentClass; $object = parentClass->new(); print $object->myMethod();
    When I do this, perl complains that it can't find myMethod. I'm betting this is something fairly simple, but I can' figure it out. Thanks.
Help !!! Symbolic Math Factroize Subroutine is clobbering my hash
1 direct reply — Read more / Contribute
by ipreferperl
on Dec 25, 2014 at 13:21
    Hello All,

    I have written a sub routine to factorize a set of equations symbolically. What appears to be happening is that in the subroutine, I am factoring an equation passed as an argument and storing the variable and coefficients associated with that variable in a hash; whose key is the variable and value is the array of coefficients. Within the routine I am using Dumper to check how the hash is getting populated. On factorizing with respect to the first variable, I see the coefficients get recorded correctly in the hash. When the next variable is factored and recorded in the has, I see the coefficients of the next variable get recorded correctly but the firs variable coefficients appears to have been clobbered.. Finally the subroutine returns an array of hashes has recorded the coefficients in an array ( value ) with respect to the variables (keys) for each equation ( equation set ). I am also having difficulty accessing the contents of the returned array of hashes from the subroutine... Any helps would be very appreciated; code is attached below -

    #!/usr/bin/perl use Data::Dumper; #use strict; my $DEBUG1=1; my @eq1; my @eq2; my @eqn_set; my @variables; my @factored_eqns; ################################################################ #2 equations( variables are x1 and x2 ) #Representations #eq1 = 2*a*b*x1 + 4*a*c*x2 + 2*a*d*x2 + 4*a*e*x2 #eq2 = 4*m*n*x1 + 2*m*o*x2 + 4*m*p*x1 + 2*m*q*x2 ################################################################ @eq1 = ("2*a*b*x1", "4*a*c*x2", "2*a*d*x1", "4*a*e*x2"); @eq2 = ("4*m*n*x1", "2*m*o*x2", "4*m*p*x1", "2*m*q*x2"); ################################################################# #Form the equation set ################################################################# @eqn_set = (\@eq1, \@eq2); ################################################################## #Return an array of hashes; hash 1 corresponds to a factored #form of eqn1; hash 2 corresponds to a factored form of eqn2 #Returns- #@factored_eqns = (%factored_eqn1, %factored_eqn2); #Where - #$factored_eqn1{"x1"} = ("2*a*b", "2*a*d"); #$factored_eqn1{"x2"} = {"4*a*c", "4*a*e"}; #$factored_eqn2{"x1"} = ("4*m*n", "4*m*p"); #$factored_eqn3{"x2"} = {"2*m*o", "2*m*q"}; ################################################################## @variables = ("x1", "x2"); @factored_eqns = &factorize(\@eqn_set,\@variables); ################################################################### #Now Dump the result of the factorization ################################################################### my $item; foreach $item (@factored_eqns){ print Dumper \%{$item}; } #################################################################### #The factorize subroutine --- #################################################################### sub factorize{ my @this_eqn_set = @{$_[0]}; my @this_variable_set = @{$_[1]}; my $equation; my $variable; my $term; my @factors = (); my %coefficient_array; my $ii=0; my @factored_rows=(); #clear the coefficient array hash undef %coefficient_array; print "Factorize.....\n"; #for each equation in the equation set foreach $equation (@this_eqn_set){ #then for each variable in the eqution foreach $variable (@this_variable_set){ #then for each term in the equation foreach $term (@{$equation}){ #if the term contains the variable currently be factored if($term =~ /\*$variable/){ #extract the variable coefficient from the term $term =~ s/\*$variable//; #save the coefficient for that variable in that term for t +hat equation push (@factors, $term); } }#End processing the term #save the coefficients for that variable in that row $coefficient_array{$variable} = \@factors; #Debug to check that the coefficient array is getting populate +d if($DEBUG1==1){ print "DEBUG1: Coefficient Array Pass $ii -\n"; print Dumper \%coefficient_array; print "D1*****D1******\n"; $ii++; } #clear the factors array for the next variable @factors=(); #the coefficient array at this satge should be a hash whose #keys are the variables and values are the coefficient terms f +or #that variable; we save the hash into the equation set retrun +array push(@factored_rows,%coefficient_array); }#End processing variable in the equation #reset the coefficient array for the the next equation undef %coefficient_array; }#End processing the equation of the equation set #return the factored rows to the calling routine return(@factored_rows); }

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 rifling through the Monastery: (8)
    As of 2014-12-28 05:37 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      Is guessing a good strategy for surviving in the IT business?





      Results (178 votes), past polls