Re: Running older cgi scripts on nginx
On Nov 7, 2013, at 3:22 PM, Angela Barone wrote: Hello, I've set up a new cloud account to get familiar with nginx and I'd like to know if it's possible to run an older cgi perl script, and if so, how would I go about doing that? I think I read somewhere that it could be done with Plack, but I can't find any instructions on how to do it. Can someone help me with this? I suggest you enter the string 'nginx cgi' into a search engine and follow the links. You can also read the nginx documentation on how to execute CGI programs here: http://wiki.nginx.org/Configuration Scroll down to the sections titled CGI, FastCGI examples, and Embedded Perl examples. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: [OT] SurfShopPRO Perl shopping cart system is now open source
On Nov 18, 2013, at 2:02 PM, SSC_perl wrote: Hi John, Thanks for getting back to me with your findings. I really appreciate it. I've gone through everything, made the changes that I could, and I have some questions to some of your remarks. You should be responding to the list, not to any individual posters. In responding to a post on this list, nobody is committing to providing follow-ups. You are using the value from readdir() without prepending the path to the file name. Unless I'm mistaken, I believe the full paths are being set in the variables, before being used by opendir. Am I misunderstanding something? Here is one of the excerpts John included in his message: forceorder.cgi:409:opendir(CARTS, $path); forceorder.cgi-410-while (my $cartfile = readdir(CARTS)) { forceorder.cgi-411-next if (-d $cartfile || $cartfile =~ /^(\.|index)/); This code is testing the path in $cartfile. However, $cartfile contains a file name (not a path) as returned by opendir. Therefore, the test '-d $cartfile' will be applied to a file in the current directory. If $path is not empty, the test will fail because the file does not exist in the current default directory. Even if it does, it is not the file that is intended to be tested. The path name should be prepended to the file name before testing, like this: next if (-d $path/$cartfile || $path/$cartfile =~ /^(\.|index)/); autoconfig.cgi:883: print font color=\33\[dir] $dir/$file/font - .htaccess installedbr\n; The variable $file is not assigned a value. I'm not seeing this. I thought it was set earlier in the security sub, but maybe I've just been staring at it for too long. If you want help on specific code, you should include that code in your message. I was unable to download the code in question from your website, but I really shouldn't have to do so. If you want help, you should make it as easy as possible for people to help you. Surf.pm:65: $cookie =~ Encode($cookie); Surf.pm:66: $value =~ Encode($value); Did you really mean to use the return value from Encode() as a regular expression? Unfortunately, I can't answer this, as I wasn't the one who wrote that code and I don't understand cookies. If someone knows the answer to this, I'd appreciate hearing it. This has nothing to do with cookies, but with the difference between assignment ('=') and regular expression binding ('=~'). Those statements are regular expression tests, but they really look like they should be assignments, since the return values are ignored. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: [OT] SurfShopPRO Perl shopping cart system is now open source
On Nov 18, 2013, at 2:02 PM, SSC_perl p...@surfshopcart.com wrote: Surf.pm:65: $cookie =~ Encode($cookie); Surf.pm:66: $value =~ Encode($value); Did you really mean to use the return value from Encode() as a regular expression? Unfortunately, I can't answer this, as I wasn't the one who wrote that code and I don't understand cookies. If someone knows the answer to this, I'd appreciate hearing it. Here is the function from Surf.pm where those two lines occur: sub SetCookies { my($cookie, $value, $exp_tickdate) = @_; if ($cookie) { $cookie =~ Encode($cookie); $value =~ Encode($value); print 'Set-Cookie: ' . $cookie . '=' . $value . ';' ; if ($exp_tickdate) { my $gmt_expdate = strftime %a, %e-%b-%Y %H:%M:%S GMT, gmtime($exp_tickdate); print expires=$gmt_expdate; } print \n; } } And here is the Encode function: sub Encode { my ($escape) = @_; my (%escapes); for (0..255) { $escapes{chr($_)} = sprintf(%%%02X, $_); } $escape =~ s/([\x00-\x20\\\+=#%;?{}|\\^~`\[\]\x7F-\xFF])/$escapes{$1}/g; #$escape =~ s/\s/+/g; return $escape; } So it looks like the purpose of line 66: $cookie =~ Encode($cookie); is to encode special characters (“+=#%;?{}|\^~`[] and \x00 through \x20 and \x7x through \xFF) in the cookie string. However, the variable $cookie is bound to the return from the Encode subroutine, not assigned to that value, and the encoded value is discarded. Therefore, if your cookies contain any of the special characters, they will not be encoded properly. Those lines should be changed to: $cookie = Encode($cookie); $value = Encode($value); Also notice that the Encode subroutine creates a 256-member hash for each execution, and uses that hash for each special character to be encoded. That is inefficient. You should create that hash one time outside of the Encode subroutine, or just create the encodings on the fly when a special character is encountered: $escape =~ s/([\x00-\x20\\\+=#%;?{}|\\^~`\[\]\x7F-\xFF])/sprintf(%%%02X,ord($1))/eg; That’s all the analysis I have time for. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Regrex Question
On Nov 25, 2013, at 10:55 AM, Mike Blezien wrote: Hello, Regular expression have never been my strong suite so hoping to get a litte help with a line in file I need to extract a portion of it. The text I need to extract from this line is November 21, 2013 from this line in the file, just the date: Posted by a href=mailto:someem...@email.com;Some Name/a on November 21, 2013 at 23:21:58:p what would be the regrex to use to extract the date from the line ? The usual advice applies: don't use regular expressions to parse HTML. However, lots of people do it anyway, myself included. Your success at extracting usable data depends upon how rigid the format of the HTML is from page to page. In your case, if the date always follows a link ('/a') followed by 'on', and the date is always followed by 'at' and a time. you can use this: if( $line =~ m{ /a \s+ on \s+ (\w+ \s \d{1,2} , \s \d{4}) \s at}x ) { print The date is $1\n; }else{ print No match\n; } Note I am using the extended regular expression syntax with the x modifier. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: remotely operate web page/website
On Nov 25, 2013, at 12:08 PM, Rajeev Prasad wrote: i need to go to a website and input some data in a specific input field, and run the query which opens a new page, i need to download and save it as an html page on my unix box. there are several blockages i am not able to figure out. 1. authentication is happening via another website, auth attempt is redirected to another website, which authenticates and stores some cookies on local PC, and loads back the page which called auth-site. 2. website needs internet explorer to operate properly. 3. this then presents menu from which i choose my choice and then that opens a form. 4. website uses javascript to build menus etc. 5. i fill some fields in the form and run it. (ok button) 6. returns result link on same page. 7. clicking the link opens the details in new page in which i am interested. websites of interest: http://xyz.abc.com/xyz/ and few more sites within same domain= abc.com authentication website: https://www.myauth.abc.com/login/?retURL=http%3A%2F%2Fxyz.abc.com%2Fxyz%2Faction.login pl advice out of sooo many modules which will help me best here? I want to learn and use just one module for my all such webpage-scraping/handling . Read about the Web-Scraping Proxy here: http://www2.research.att.com/sw/tools/wsp/ -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Regex not working correctly
On Dec 11, 2013, at 7:34 AM, punit jain contactpunitj...@gmail.com wrote: Hi, I have a requirement where I need to capture phone number from different strings. The strings could be :- 1. COMP TEL NO 919369721113 for computer science 2. For Best Discount reach 092108493, from 6-9 3. Your booking Confirmed, 9210833321 4. price for free consultation call92504060 5. price for free consultation call92504060number I created a regex as below :- #!/usr/bin/perl my $line= shift @ARGV; if($line =~ /(?:(?:\D+|\s+)(?:(91\d{10}|0\d{10}|[7-9]\d{9}|0\d{11})|(?:(?:ph|cal)(\d+|(?:(?:(91\d{10}|0\d{10}|[7-9]\d{9}|0\d{11})|(?:(?:ph|cal)(\d+)))(?:\D+|\s+))/) { print one = $1; } It works fine for 1, 2,3 and prints number however for 4 and 5 one I get number in $2 rather than $1 tough I have pipe operator to check it. Any clue how to fix this ? Your first step is to rewrite the regular expression using the extended syntax x modifier and add some whitespace: if($line =~ m{ (?: (?: \D+ | \s+ ) (?: ( 91\d{10} | 0\d{10} | [7-9]\d{9} | 0\d{11} ) | (?: (?: ph | cal ) (\d+) ) ) ) | (?: (?: ( 91\d{10} | 0\d{10} | [7-9]\d{9} | 0\d{11}) | (?: (?: ph | cal ) (\d+) ) ) (?: \D+ | \s+ ) ) }x ) { Then maybe you will have some hope of figuring out why it doesn’t work (I certainly can’t). I suggest you break it up into a series of if-then-else statements: if( $line =~ /91\d{10} | \\d{10} | [7-9]\d{9} | 0\d{11} ) { $number = $1; }elsif( $line =~ (?:ph|cal)\d+ ) { $number = $1; }elsif( … ) { }else{ print “No match for $line”; } You don’t need to do it all in one regex. Debugging each of those smaller regexes will be easier than debugging the whole thing. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: baby perl to get the right date
On Jan 27, 2014, at 11:32 PM, Luca Ferrari fluca1...@infinito.it wrote: Hi all, often I find myself writing something like the following to get the human date: my ($day, $month, $year) = (localtime())[3..5]; $month++, $year += 1900; print \nToday is $month / $day / $year \n; I was wondering if there's a smarter pattern to get the right value in one single line. At least there's no simple map I can think of. The localtime() function in scalar context returns a string containing the date and time. See ‘perldoc -f localtime’ for details. For example, here’s what I put at the beginning of my program to print out the date and time the run started: print “Run started at “, scalar localtime(), “\n”; -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: regex headache
On Feb 3, 2014, at 12:30 PM, Paul Fontenot wrote: Hi, I am attempting to write a regex but it is giving me a headache. I have two log entries 1. Feb 3 12:54:28 cdrtva01a1005 [12: 54:27,532] ERROR [org.apache.commons.logging.impl.Log4JLogger] 2. Feb 3 12:54:28 cdrtva01a1005 [12: 54:27,532] ERROR [STDERR] I am using the following ^\w+\s+\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2}\s+\w+\s+\[\d{1,2}:\s+\d{1,2}:\d{1, 2},\d{3}\]\s+\w+\s+\[[a-zA-Z0-9.]\] My problem is this greedy little '.' - I need to just be a period. How do I match #1 and not match #2? You appear to be making the job too difficult. The only difference between lines 1. and 2. is the last column. To differentiate those two, you can do this (assuming the string is in $_): if( /\[STDERR\]/ ) { # process line 2 }else{ # process line 1 } Do you really need to match each field in the entire line? If so, I would try splitting the lines on whitespace and extracting the columns you need that way. Whether or not that works depends upon: 1) how much variation there can be in your log entries, and 2) what exactly you need to extract from each entry. Fixing that regex may not be the most productive approach in the long term. As for your specific question, a period in a character class (e.g., [.]) will match a period. A period in the regex pattern will match any character (except possibly a newline). To match a period character, escape the period: /\./ -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: OO perl programming
On Feb 13, 2014, at 12:27 PM, Uri Guttman wrote: On 02/13/2014 12:39 PM, Janek Schleicher wrote: Am 05.02.2014 23:30, schrieb kavita kulkarni: Can somebody suggest me good book to learn/practice object oriented Perl programming. The usual answer is to study computer science. OO programming is the same independet of language. actually that isn't totally true. the concepts are fairly language independent but some languages have better support for OO than others. in particular it isn't hard to do OO even assembler (which i did) in that i grouped common data together and called subs via attached pointers. the biggest feature (which i generally don't like anyway) is inheritance and that pretty much has to be in the language to be effective. Yup. The four pillars of Object Oriented Programming are said to be: 1. Encapsulation 2. Data hiding 3. Polymorphism 4. Inheritance Perl doesn't really do data hiding very well (google for Larry Wall shotgun), but it does support the other three OK. I have not programmed in Perl using OO techniques in years. I think I have written one big Perl program that uses OO inheritance in 15 years. (Just lucky, I guess :) CPAN modules should be OO nowadays, just to avoid namespace clashes (all the good function names are taken). -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: regex to get version from file name
On Feb 21, 2014, at 6:21 AM, Wernher Eksteen crypt...@gmail.com wrote: Hi all, From the below file names I only need the version number 1.2.4 without explicitly specifying it. check_mk-1.2.4.tar.gz check_mk-agent-1.2.4-1.noarch.rpm check_mk-agent-logwatch-1.2.4-1.noarch.rpm check_mk-agent-oracle-1.2.4-1.noarch.rpm mk-livestatus-1.2.4.tar.gz mkeventd-1.2.4.tar.gz What regex can I use to obtain only the string value 1.2.4 from the file names (or whatever future versions based on the 3 numbers separated by 3 dots, [0-9].[0-9].[0-9]? Here’s one that will do any number of digits, provided they are preceded by a hyphen and followed by a hyphen or period (like all of your samples): /-([\d.]+)[.-]/ -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: regex to get version from file name
On Feb 23, 2014, at 5:10 AM, Wernher Eksteen crypt...@gmail.com wrote: Hi, Thanks, but how do I assign the value found by the regex to a variable so that the 1.2.4 from 6 file names in the array @fileList are print only once, and if there are other versions found say 1.2.5 and 1.2.6 to print the unique values from all. From that I want to get the value 1.2.4 and assign it to a variable, if there are more than one value such as 1.2.5 and 1.2.6 as well, it should print them too, but only the unique values. My attempt shown below to print only the value 1.2.4 is as follow, but it prints out 1.2.41.2.41.2.41.2.41.2.41.2.4 next to each other, if I pass a newline to $i such as $i\n it then prints 11 ? foreach my $i (@fileList) { print $i =~ /\b(\d+\.\d+\.\d+)\b/; } The parentheses in the above regular expression cause the matched substrings to be assigned to $1. If you wish to print those values, print $1 or assign the value of $1 to another variable and print it: if( $i =~ /\b(\d+\.\d+\.\d+)\b/ ) { print “$1\n”; } If you wish to find all of the unique values of what is captured, use the values as keys in a hash and print the keys after all the lines have been processed (untested): my %unique; foreach my $i (@fileList) { if( $i =~ /\b(\d+\.\d+\.\d+)\b/ ) { $unique{$1}++; } for my $number ( sort keys %unique ) { print “Version $number had $unique{$number} files\n”; } -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Calculate MD5 checksum of a remote and local file using FTP
On Feb 23, 2014, at 7:09 PM, Shaji Kalidasan shajiin...@yahoo.com wrote: Dear Perlers, I made some improvements in my code (now I am checking the file size of remote file) but still can't figure out how to calculate the MD5 hash of a remote file. You cannot calculate the MD5 digest of a file on a remote server. In order to calculate the MD5, you need access to all of the bytes of the file. To access all of the bytes, you need to download the file to your local computer. Since you are already downloading the file and calculating the MD5 of the local copy, it doesn’t do you any good to do it again. That will only confirm that the download succeeded (or you got exactly the same error twice.) You don’t need an MD5 calculation for that; you can just compare the two copies. You need to get someone with access to the server to compute the MD5 of the file on the server, then publish the MD5 value of the copy on the server. Then you can compare the MD5 of your local copy and verify that you have the same file as on the server. If you can’t arrange that, then some other approach is needed. You need to describe in more detail what you are trying to accomplish. The Digest::MD5::File module will calculate the MD5 digest of a URL, but it is just going to download the file before it does that. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: check list if values meet criteria
On Feb 25, 2014, at 2:30 PM, Bill McCormick wrote: What would be the perl'ish way using map or some other sugar to check if a list of values meet some criteria? Instead of doing something like my @issues = qq(123,456,a45); my $max = 999; for (@issues) { die if $_ 0 or $_ $max; } I want to check if each list item is numeric and 0 but less than $max. Cheers! grep is the Perl function for testing a list of values against some criteria. perldoc -f grep 'grep BLOCK LIST' will return all of the items in LIST that result in a true value when BLOCK is evaluated. In scalar context, grep returns the number of items that evaluated to true, so you can either save all of the true-ish items or just get a count. For example (untested): my @fail = grep { $_ =~ /\D/ || $_ = 0 || $_ = $max } @issues; Now @fail contains any member of @issues that fails any of the three tests: 1) contains a non-digit, 2) is less than or equal to zero, 3) greater than or equal to $max If @fail is empty, everybody passed (that is, evaluated to false!) -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: file edit
On Feb 26, 2014, at 7:59 AM, jet speed speedj...@googlemail.com wrote: Chaps, Any quick one liner code in perl were i can get rid off the before and after wwn each line for file as below file --- device name lz_09_red_e10 vsan 200 * fcid 0xef0013 [pwwn 50:00:00:00:99:00:66:7a] * fcid 0xegg015 [pwwn 10:00:00:55:99:a8:d9:c4] [ pe-tgh10-hostb] device name lz_09_blue_e10 vsan 200 * fcid 0xef0013 [pwwn 50:00:00:00:99:00:66:7b] [ pe-tgh10-hostc] * fcid 0xegg015 [pwwn 10:00:00:55:99:a8:d9:c9] desired output - device name lz_09_red_e10 vsan 200 50:00:00:00:99:00:66:7a 10:00:00:55:99:a8:d9:c4 device name lz_09_blue_e10 vsan 200 50:00:00:00:99:00:66:7b 10:00:00:55:99:a8:d9:c9 Appreciate any help on this. s/.*\[pwwn (.*?)\].*/$1/; or the more specific s/.*\[pwwn ([0-9a-f:]+)\].*/$1/; -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: match not matching
On Feb 28, 2014, at 9:13 PM, Bill McCormick wpmccorm...@gmail.com wrote: Can somebody help me understand this? Given this loop, and the logged output following ... my $found; for( @$products ) {; $found = $$_ =~ m|$project|; $dump = Data::Dumper-Dump([$_, $project, $$_, $found]); $logger-trace(qq(dump=$dump)); } I can't explain why $found is not true on the 3rd pass. Does this have something to do with the way I'm dereferencing the blessed object? SVN.Hooks - dump=$VAR1 = bless( do{\(my $o = 'FS1100-S1')}, 'RPC::XML::string' ); $VAR2 = 'STABLE/FS1100-S3/RSLOGIX_5000/'; $VAR3 = 'FS1100-S1'; $VAR4 = ''; SVN.Hooks - dump=$VAR1 = bless( do{\(my $o = 'FS1100-S2')}, 'RPC::XML::string' ); $VAR2 = 'STABLE/FS1100-S3/RSLOGIX_5000/'; $VAR3 = 'FS1100-S2'; $VAR4 = ''; SVN.Hooks - dump=$VAR1 = bless( do{\(my $o = 'FS1100-S3')}, 'RPC::XML::string' ); $VAR2 = 'STABLE/FS1100-S3/RSLOGIX_5000/'; $VAR3 = 'FS1100-S3'; $VAR4 = ''; You have inverted the regular expression. You want this: for( @$products ) {; $found = $project =~ m|$$_|; -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Reading a config file and exporting it updated with the new/changes values in the same format.
On Mar 3, 2014, at 8:47 AM, Wernher Eksteen wrote: Hi Shlomi, Thank you for the pointers. I do want to learn Python as well when I get a chance. This framework I'm writing now will automate things to a great extend eventually freeing up loads of my daily operations time so I can focus on more interesting things. I'm really not expecting the code to be written for me, mere pointers as you did (with some examples would be a plus) is all that's needed for me to look into that and take it further. If you want some examples of how to parse your config files, then you should show us some examples of those config files. How to best parse the files depends wholly upon the format of the files. Some formats are easy to parse; other formats are more difficult. Nobody can advise you without seeing some examples of the files, and how much variation occurs in the format or content of the possible files you will encounter. Good luck. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Delete first line when blank
On Mar 7, 2014, at 1:58 PM, s...@missionstclare.com wrote: I have some text files from which I would like to remove the first line, but only if it's blank. Any hints? I tried a few things, but the results haven't quite been satisfactory. You should be able to do that in just a few lines of Perl: 1. Open the existing file for reading. 2. Open a new file for writing. 3. Read the first line in the input file. 4. If the first line is not blank, write it to the output file. 5. Read the remaining lines from the input file and write to the output file. 6. Close both files 7. Optionally: rename both files to give the new file the same name as the old file. If you don't understand any of the steps, just ask. If you have trouble, post your program here, and someone will be able to help you. Good luck. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: regexp puzzle
On Mar 7, 2014, at 10:05 PM, Bill McCormick wpmccorm...@gmail.com wrote: I have the following string I want to extract from: my $str = foo (3 bar): baz; and I want to to extract to end up with $p1 = foo; $p2 = 3; $p3 = baz; the complication is that the \s(\d\s.+) is optional, so in then $p2 may not be set. getting close was my ($p1, $p3) = $str =~ /^(.+):\s(.*)$/; You can make a substring optional by following it with the ? quantifier. If you substring is more than one character, you can group it with capturing parentheses or a non-capturing grouping construct (?: ). Here is a sample, using the extended regular expression syntax with the x option: my( $p1, $p2, $p3 ) = $str =~ m{ \A (\w+) \s+ (?: \( (\d+) \s+ \w+ \) )? : \s (\w+) }x; if( $p1 $p3 ) { print “p1=$p1, p2=$p2, p3=$p3\n”; }else{ print “No match\n”; } Always test the returned values to see if the match succeeded. So if '(3 bar)’ is not present, does the colon still remain? That will determine if the colon should be inside or outside the optional substring part. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: RegExp
On Mar 8, 2014, at 4:50 AM, rakesh sharma rakeshsharm...@hotmail.com wrote: Hi all, how do you get all words starting with letter 'r' in a string. Try my @rwords = $string =~ /\br\w*?\b/g; -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Internet Search
On Mar 14, 2014, at 5:28 AM, Anant kumar anant.singh1...@gmail.com wrote: Hi everyone, I am trying to write a script to search on the internet for different keywords (like Organism name, metabolic reactions and Genes involved). Can anyone suggest me how to proceed. I don't want to attach the link to any website like what CGI module perform. Just want to search and store it any format like XML etc. Any help will be appreciated, Sincerely yours, Anant Kumar B.Tech; Biotechnology This appears to be a new topic unrelated to ‘Fail to match mixed quote pattern’. You should start a new thread for a new topic (as I have done). What you are asking about sounds like a search engine. Do you want to use an existing search engine, such as Google, Bing, or Duckduckgo, or write your own? Google, for example, has a search API that will return search results in JSON or XML formats. You will need a Google Account. Information here: https://developers.google.com/custom-search/. There is also a Perl module (WWW::Google:CustomSearch) to help. See here: http://search.cpan.org/~manwar/WWW-Google-CustomSearch-0.11/lib/WWW/Google/CustomSearch.pm Good luck. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: arbitrary sort
On Mar 25, 2014, at 6:55 AM, shawn wilson ag4ve...@gmail.com wrote: i want to sort an array for certain key words first and then alphabetically. my @foo = qw/foo bar baz first second third/; foreach my $i (sort {$a cmp $b} @foo) { print $i\n; } How do I make 'first', 'second', and 'third' come before the rest? (I'm actually dealing with a hash) You need to write a sort comparison function that will return: -1 if $a is a primary key and $b is not +1 if $b is a primary key and $a is not a normal comparison value if either both or neither are a primary key Here is one way: #!/usr/bin/perl use strict; use warnings; my @keys = qw( foo bar baz first second third ); my %primary = ( first = 1, second = 1, third = 1); my @sorted; @sorted = sort { if( ! ($primary{$a} xor $primary{$b}) ) { return $a cmp $b; }elsif( $primary{$a} ) { return -1; }else{ return +1; } } @keys; print Sorted: , join(', ',@sorted), \n”; You could also prepend ‘1’ to your primary keys and ‘2’ to the other keys, do the sort, then strip the digits. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: arbitrary sort
On Mar 25, 2014, at 7:56 AM, shawn wilson ag4ve...@gmail.com wrote: Thanks (y'all). Though, I like this one best I think. BTW, Jim's isn't exactly correct: my @keys = qw( foo bar second baz first third ); my %primary = ( second = 1, first = 1, third = 1); And then the output becomes: Sorted: first, second, third, bar, baz, foo Which isn't correct. I humbly beg to differ. Your specification was to sort ‘first’, ‘second’, or ‘third’ before other keys, and the solution I provided does exactly that, sorting ‘first’, ‘second’, and ‘third’ in alphabetic order before the other keys. The values assigned to the %primary hash are irrelevant and are not used in any comparison. The existence of the key,value pair in the hash is used to specify which keys are the primary ones. If you want to specify what order the primary keys should occur, rather than simple alphabetic order, then you will have to modify the program: #!/usr/bin/perl use strict; use warnings; my @keys = qw/foo bar baz first second third/; my %primary = ( first = 3, second = 2, third = 1); # different values for each key giving sort order (1, 2, 3, etc.) my @sorted; @sorted = sort { if( $primary{$a} $primary{$b} ) { return $primary{$a} = $primary{$b}; }elsif( $primary{$a} ) { return -1; }elsif( $primary{$b} ) { return +1; }else{ return $a cmp $b; } } @keys; print Sorted: , join(', ',@sorted), \n; Producing: Sorted: third, second, first, bar, baz, foo -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: use sys::virt module to manage VM in kvm
On Mar 26, 2014, at 6:30 PM, Benjamin Fernandis benjo11...@gmail.com wrote: Hi, I am new with perl and we have virtual machines in our infra. i want to use perl sys::virt module to manage them, means to shutdown / start vm by script and for that i wrote below small code. #!/usr/bin/perl # use strict; use warnings; use Sys::Virt; my $vmm = Sys::Virt-new(uri = qemu:///system); my @domains = $vmm-list_domains(); foreach my $dom (@domains) { print Domain , $dom-get_id, , $dom-get_name, \n; } my $vm = 'win7'; $vm = $vmm-destroy(); and when i run it , i got below error. Domain 10 win7 Can't locate object method destroy via package Sys::Virt at vm.pl line 18. can you please guide me that where i made mistake. please correct me if something syntax problem or. Thanks Ben That error message indicates that the Sys::Virt class has no method called ‘destroy’. That corresponds with the documentation of the class on cpan.org. Why are you calling that method? Are you running the latest version of the module? The syntax of the program is fine, as indicated by the fact that it does compile. However, it is unnecessary to assign a value to $vm when it is declared, and then immediately overwrite that value with the return value of $vmm-destroy(). -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: find specific line from file
On May 20, 2014, at 4:19 PM, Benjamin Fernandis wrote: Hi, I want to fetch rawuuid from below file for each partition name. I tried to use while loop and all but no luck. example : partition name : ada0p2 rawuuid: 5899824d-e019-11e3-9cbc-08002731cc9a file : Geom name: ada0 This seem like a simple job for a couple of regular expressions. How did you go about extracting the partition name and rawuuid value? Please post your code in your next message so we can give you some helpful suggestions. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: CPAN unavailable
On May 20, 2014, at 6:41 PM, Yonghua Peng sys...@mail2000.us wrote: I probably meant search.cpan.org doesn't work. Try picking a different mirror. These are the ones I am using: http://httpupdate35.cpanel.net/CPAN/ http://mirrors.gossamer-threads.com/CPAN/ http://cpan.cs.utah.edu/ -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: find specific line from file
Benjamin: Please post messages to the list, not individual members. On May 20, 2014, at 6:51 PM, Benjamin Fernandis benjo11...@gmail.com wrote: Hey Jim, I tried to use while loop to read file line by line, but facing problem to get exact phrase or a way to start reading from predefined partition name and then fetch next coming rawuuid. Thanks Ben I would: 1. Read the file line-by-line. 2. Look for partition name and save in a variable 3. Look for rawuuid name and combine with previously saved partition name. 4. Repeat until no more lines to read. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: How to parse C#, javascript, lisp source code for quoted literal strings
On May 22, 2014, at 2:04 AM, siegfr...@heintze.com siegfr...@heintze.com wrote: I need to extract some information from source code. How can I write a perl regular expression that will match a literal string in languages like C#, javascript, java and lisp? Here is my naive approach: /[^]*/ This of course does not accommodate backslashes in the string that perl, C, C# javascript use. \sdfds\\\r\\t\\m. How can I write a regular expression in perl to look for a double quoted literal string in these languages? The Regexp::Common module, available from cpan.org, has several useful categories of regular expressions. Among these is Regexp::Common::delimited for finding delimited strings, which you may find useful. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Append new line at end of non-quoted text
On May 23, 2014, at 2:45 PM, Sherman Willden wrote: Disclaimer: I am 67 and not in school. I am doing this for my own satisfaction. How do I get a new line at the end of a non-quoted text. I am doing the following: Use Math::Trig; print pi * 2; print \n; How do I get the new line on the same line of code? I could do my $my_pi_times_two = pi * 2; print $my_pi_times_two\n; but that seems to be overkill. There are several ways. 1. You can use the new 'say' function, instead of 'print', which automatically adds a newline to every output. Put 'use feature say' at the beginning of your program: say pi * 2; 2. You can print a list: print pi * 2, \n; 3. You can concatenate a newline onto the end of your string: print pi * 2 . \n; 4. You can use the printf function: printf %f\n, pi * 2 -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Append new line at end of non-quoted text
Please post messages to the list, not to me personally. That way, you will get better answers sooner. On May 23, 2014, at 3:13 PM, Sherman Willden wrote: Thank you, Jim; How do I get rid of the warning message without getting rid of the -w switch? Use the 'use warnings;' pragma in your program instead of '-w' on the first line. That way, you can control which messages are issued. I do not know if it is possible to get rid of the warnings you are seeing. I do not use the 'say' command, but prefer print, and use one of the other techniques I listed. See 'perldoc use warnings' and 'perldoc perllexwarn' for more details about 'use warnings'. The code is last in this text. The output is as follows: perl -c nums.pl Unquoted string say may clash with future reserved word at nums.pl line 4. nums.pl syntax OK perl nums.pl Unquoted string say may clash with future reserved word at nums.pl line 4. 6.28318530717959 6.28318530717959 6.28318530717959 6.283185 #!/usr/bin/perl -w use Math::Trig; use feature say; say pi * 2; print pi * 2, \n; print pi * 2 . \n; printf %f\n, pi * 2; -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: How to implement locks/gates/semaphores to alleviate race conditions?
On May 24, 2014, at 9:40 AM, siegfr...@heintze.com wrote: I have multiple processes running cygwin/bash that are accessing the same files in a certain directory. I want to create a lock or semaphore or gate to serialize access to this directory so that no two (or more processes) can access the directory at any one time. As soon as the first process running bash grabs the lock using perl, the perl program exits, bash creates a file, and bash then needs to call a second perl program to release the lock or event so that only one of the other blocking processes can now grab the lock. Can someone recommend a way to do this in perl or python? How would I do this? I can think of several ways and they all sound difficult (1) Create a memory resident Win32 Event. This is tedious because the lock will be released when the perl program exists. I need to keep the lock until bash executes a second perl program. I suppose bash could call perl as a child process which would then grab the Win32 event and wait on a socket or a second win32 event until the parent bash program is ready to release the first win32 Event. This sounds much to complicated (and OS specific). Please tell me there is an easier way! (2) I could use the resource manager built into SQL Server. I don't know how to do this from perl. Is it possible? I don't like this option because it not only requires SQL Server be installed and running but only works on windows. (3) Is there a way to do it with the Microsoft Access database? While this has the advantage of not requiring a server be running (like SQL Server), it is not OS neutral (and I don't know how to do it). (4) Perhaps there is cygwin implementation of Unix style semaphore that I can call from perl? Are there any packages for this? This still has the problems of option #1. (5) Gollly! I don't like any of the above options! They are all so complicated. Is there something simpler? I would try creating a “lock” file in the directory. File creation is pretty fast. You can use the file creation or modification time to recover from a stuck lock if you know about how long a lock should be held. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Brackets in scalar and array
On May 29, 2014, at 1:20 PM, James Kerwin wrote: Hello all, long time lurker, first time requester... I have a Perl exam tomorrow and came across a question that I just cannot find an answer to (past paper, this isn't cheating or homework etc.). Explain the difference between: ($test)=(@test); And $test=@test; If anybody could shed any light on this I'd be very grateful. The difference is the context of the assignment: scalar or list, and how @test (or (@test)) is evaluated in that context. In the first statement ($test) = (@test), the parentheses around $test in the left-hand side (LHS) of the assignment places the evaluation of the right-hand side (RHS) in list context. In list context, with two lists on either side of the assignment operator (=), assignment is made from each element on the RHS to the corresponding element on the LHS. Therefore, the one and only element on the LHS ($test) gets assigned the value of the first element of the RHS, and $test ends up with the value of $test[0]. In the second statement, the assignment is done in scalar context, and the RHS is evaluated in scalar context. A list evaluated in scalar context returns the number of elements in the list, and $test is assigned the value ($#test+1). Note that the parentheses around @test in the first statement are irrelevant. The context is list with or without them. Try it yourself: % perl -e '@t=qw(1 2 3);$t=@t;print qq($t\n);' 3 % perl -e '@t=qw(1 2 3);($t)=@t;print qq($t\n);' 1 % perl -e '@t=qw(1 2 3);($t)=(@t);print qq($t\n);' 1 -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Brackets in scalar and array
On May 29, 2014, at 3:34 PM, Sherman Willden wrote: Maybe I'm missing the point but isn't the following code the problem's answer? Please let me know if I am off base. Just a bit off (see below). #!/usr/bin/perl my @test = a b c; That is a scalar on the right-hand side. You end up with a one-element array in which the first and only element is the string 'a b c'. Shawn and I were using the qw() operator, which splits a string on whitespace and returns a list: my @test = qw(a b c); which is equivalent to and shorter than: my @test = ( 'a', 'b', 'c'); -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: how to create a text progress status line that updates on the same line in Perl?
On Jun 10, 2014, at 2:59 PM, Kenneth Wolcott wrote: Hi All; how to create a text progress status line that updates on the same line in Perl? I know that this questions is probably not well-posed, but I hope you get what I'm after. I'd like to do what application installers do, describing the status, updating the status occasionally, but on the same line overwriting what was there earlier. Do I need to use the hex or oct form of the backspace (octal 010) for each character that I want to overwrite? Quick answer: 1. Use print (not say), 2. Turn on autoflushing ($|++), 3. Put a carriage return character (\r) at the beginning of the line, 4. Don't put a new line (\n) at the end of the line, and 5. Either use the same, fixed number of characters each time or add spaces at the end of short lines to erase any characters left over from a previous line. Check this out: perl -e '$|++;for (0..20) { $x=q(=)x$_;$y=q( )x(20-$_); print qq(\r$x$y);sleep(1);}' -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: bash to perl for cgi
On Jun 17, 2014, at 1:10 AM, Philippe Rousselot rousse...@rousselot.org wrote: Hi, I know nothing about perl and I have a problem with a cgi script for a website called geneweb (genealogy stuff). I moved from one web site to another and now the site does not work and give me a 500 error message. Do you have access to the web server logs? Those could be very helpful in diagnosing your error. the script I need to call the program is the following ~~ #!/bin/sh DIR=/homez.xxx//www/geneweb607/gw cd $DIR $DIR/gwd -cgi 2/dev/null ~~ I guessed, but I may be wrong that I cannot use a sh script (I checked for files and folders rights) I am no web expert, but as far as I know, there is no reason why you can’t run a shell script as a CGI program. However, there may be security issues, and you may have reconfigure your server. You are probably better off using Perl instead. Could someone give me a translation in perl of this script so I can try out this idea Here is a Perl program that does the same thing as your shell script: #!/bin/env perl use strict; use warnings; my $dir = q(/homez.xxx//www/geneweb607/gw); system(“cd $dir;$dir/gwd -cgi 2/dev/null”)’ Good luck! -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Stopping undefined warnings
On Jun 17, 2014, at 1:02 PM, SSC_perl wrote: What's the best way to stop undefined warnings for code like this: $data-{'image'} = CopyTempFile('image') if ($main::global-{'admin'} $main::global-{'form'}-{'image_upload'} ne ''); CGI::Carp gives the following: [Tue Jun 17 14:54:36 2014] admin.cgi: Use of uninitialized value in string ne at admin.cgi line 219. I know that I can surround the section with { no warnings 'uninitialized'; ... } or I could add a check for defined-ness as follows: $data-{'image'} = CopyTempFile('image') if ($main::global-{'admin'} defined $main::global-{'form'}-{'image_upload'} $main::global-{'form'}-{'image_upload'} ne ''); Is there a better way to stop this warning in situations like this? I'd like to keep these warnings from filling up the log. Best and better are subjective terms about which people will argue. Me, I would split your one, long line into several lines and use a temporary variable to hold the possibly undefined value and assigning '' to it if it is undefined: my $upload = $main::global-{'form'}-{'image_upload'} || ''; if ($main::global-{'admin'} $upload ne '' ) { $data-{'image'} = CopyTempFile('image'); } I find that much more readable and will not generate any undefined warnings. Note that later Perls can use the // operator in the first line to test the definedness of the hash value: my $upload = $main::global-{'form'}-{'image_upload'} // ''; but there is no practical instance in this case. There would be if you needed to distinguish zero or '' from undef. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Need to Grep only fail count from the Pattern.
On Jun 25, 2014, at 12:11 AM, Uday Vernekar vernekaru...@gmail.com wrote: Dear Ron, You are better off addressing your questions to the entire mailing list, rather than asking information from one person. Ron is not obligated to help you and may not be available, but others may be willing to help you. How wud i grep the string | 72| Traffic Test |1| 561| from log file which is Very large. You would: 1. open the file for reading 2. read each line in the file 3. check each line for your desired pattern That is what grep does. By doing this in Perl, you save having to create another process. You can combine the step of finding the pattern and extracting information from the desired line. You can also quit after you have found the line you are seeking, if you only need to find one match; grep will continue to read the rest of the file looking for more matches. Let us know if you have problems with any of these steps. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Need to Grep only fail count from the Pattern.
On Jun 26, 2014, at 2:05 AM, Uday Vernekar wrote: Please suggest if any Corrections Needed. There are several improvements you could make. [code] #!/usr/bin/perl use 5.10.0; use strict; use warnings; #Pattern #U/A/S|Test|Test |Loop | Run |Pass |Fail | Arguments # | # |Name |Count|Count|Count|Count| #-++---+-+-+-+-+--- # | 72| Traffic Test |1| 561| 560|1| (none) my $pattern; $pattern is not a good variable name for holding a string that matches some pattern. The 'pattern' is embedded in your regular expression. I would use something like $match or $found. open (my $Log_file, '', '/tmp/EO-PCPE-23-10GT') || die Couldn't open /tmp/EO-PCPE-23-10GT\n\t $!; When posting programs to a mailing list, you can use the special DATA file handle and put the lines at the end of your program after a line containing just a '__DATA__' marker. That way, people who do not have access to your data file will be able to run your program. while($Log_file) It is usually better to use explicit variables: while( my $line = $Log_file ) { if( $line =~ ... ) { { if($_ =~ m/^(.+?)\|(.+72)\|(.+?)\|(.+?)\|(.+[0-9]|[0-9]|[0-9])\|(.+[0-9]|[0-9]|[0-9])\|(.+?)\|(.+?)$/) This reqular expression is very long and hard to read. You seem to want match any line that: 1. Has seven '|' characters delimiting eight fields. 2. Has '72' in field 2. 3. Has numbers in fields 5 and 6. I would recommend first splitting the line, then checking the individual fields for their desired content. In addition, the regex fragment '(.+[0-9]|[0-9]|[0-9])' may not be doing what you think. This fragment will match: 1. At least one character followed by a digit (0-9) OR 2. A digit (0-9) OR 3. A digit (0-9) The | character is alternation. You seem to be treating it as concatenation. The second and third alternatives are identical, and the third one is redundant. If you want to match three successive digits, these will all work: [0-9][0-9][0-9] [0-9]{3} \d\d\d \d{3} { $pattern=$_; } } print Pattern Found:\n$pattern; my $uas=(split /\|/, $pattern)[0]; $uas =~ s/^\s+//; my $test=(split /\|/, $pattern)[1]; $test =~ s/^\s+//; my $test_name=(split /\|/, $pattern)[2]; $test_name =~ s/^\s+//; my $loop_count=(split /\|/, $pattern)[3]; $loop_count =~ s/^\s+//; my $run_count=(split /\|/, $pattern)[4]; $run_count =~ s/^\s+//; my $pass_count=(split /\|/, $pattern)[5]; $pass_count =~ s/^\s+//; my $fail_count=(split /\|/, $pattern)[6]; $fail_count =~ s/^\s+//; my $arguments=(split /\|/, $pattern)[7]; $arguments =~ s/^\s+//; You can perform the split only once. You can also include optional whitespace in the delimiter string, which means the saved substrings will not include the whitespace: my( $uas, $test, $test_name, $loop_count, $run_count, $pass_count, $fail_count, $arguments ) = split('\s*\|\s*',$line); print '-' x 30, \n; print Test Data \n; print '-' x 30, \n; print UAS : $uas\n; print Test : $test\n; print Test Name : $test_name\n; print Loop Count : $loop_count\n; print Run Count : $run_count\n; print Pass Count : $pass_count\n; print Fail Count : $fail_count\n; print Arguments : $arguments\n; print '-' x 30, \n; print RESULTS \n; print '-' x 30, \n; You can use a 'HERE' document to print these lines: print EOS; -- Test Data -- UAS : $uas Test : $test Test Name : $test_name Loop Count : $loop_count Run Count : $run_count Pass Count : $pass_count Fail Count : $fail_count Arguments : $arguments -- RESULTS -- EOS So putting that altogether, here is an improved program: [code] #!/usr/bin/env perl use strict; use warnings; while( my $line = DATA ) { chomp($line); next if $line =~ /^-/; my @f = split('\s*\|\s*',$line); next unless scalar @f == 8; my( $uas, $test, $test_name, $loop_count, $run_count, $pass_count, $fail_count, $arguments ) = @f; if( $test eq '72' ) { print EOS; -- Test Data -- UAS : $uas Test : $test Test Name : $test_name Loop Count : $loop_count Run Count : $run_count Pass Count : $pass_count Fail Count : $fail_count Arguments : $arguments -- RESULTS -- EOS if( $fail_count != 0 $run_count = 0 ) { print Result: Fail\n; }elsif( $fail_count == 0 $run_count 0 ) { print Result: Pass\n; } } } __DATA__ U/A/S|Test|Test |Loop | Run |Pass |Fail | Arguments | # |Name
Re: Need to Grep only fail count from the Pattern.
On Jun 30, 2014, at 2:44 AM, Uday Vernekar vernekaru...@gmail.com wrote: please Explain next if $line =~ /^-/; “Skip this input line if it starts with a dash ‘-‘ character.” my @f = split('\s*\|\s*',$line); Break the input line into files separated by the vertical pipe character ‘|’ and any whitespace before or after the pipe character, i.e., don’t include the whitespace in the extracted fields. next unless scalar @f == 8; “Skip this input line unless it consists of exactly 8 fields.” -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: one line script for word count
On Jun 30, 2014, at 11:57 AM, Sunita Pradhan wrote: Hi I want to count number of occurrences of one word in a line within one single line of perl script . My code : $c++ if ($line =~ /\s+$w\s+/g); print count $c\n; Try this: $c = () = $line =~ /\b$w\b/g; -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: one line script for word count
On Jun 30, 2014, at 12:17 PM, Sunita Pradhan wrote: Thanks Jim. It is working but why a array is required here? Please respond to the list and not to me personally. That way, everybody will see your question, and somebody else can answer. Try this: $c = () = $line =~ /\b$w\b/g; The empty array is necessary to put the return value of the binding operator '=~' into list context. Without it, the return value is in scalar context and returns just a 1 ('true'). In list context, the binding operator returns a list of the matched strings. When that is converted to scalar context by the assignment to $c, it becomes the size of the list. See 'perldoc perlop', search for Regexp Quote-Like Operators, and scroll down to the section titled 'Matching is list context'. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Need to Grep only fail count from the Pattern.
On Jul 1, 2014, at 1:26 AM, Uday Vernekar vernekaru...@gmail.com wrote: The script works fine without next if $line =~ /^-/; How it helps. It skips the line containing all dashes which separate the data lines. The script works without it because that line will fail the next test: ‘next unless scalar @f == 8’. However, checking the line for a single dash character at the beginning will be faster than trying to split the line with a regular expression and testing the number of fields that result. If you are only looking at a small number of lines, it probably doesn’t matter. In a large number of larger files, it might. In general, when trying to parse complex files, it is best to identify and eliminate unwanted lines before trying to extract data from those that are relevant. Not doing so can lead to unwanted errors or program crashes in the future. On Mon, Jun 30, 2014 at 9:06 PM, Jim Gibson jimsgib...@gmail.com wrote: On Jun 30, 2014, at 2:44 AM, Uday Vernekar vernekaru...@gmail.com wrote: please Explain next if $line =~ /^-/; “Skip this input line if it starts with a dash ‘-‘ character.” my @f = split('\s*\|\s*',$line); Break the input line into files separated by the vertical pipe character ‘|’ and any whitespace before or after the pipe character, i.e., don’t include the whitespace in the extracted fields. next unless scalar @f == 8; “Skip this input line unless it consists of exactly 8 fields.” -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: List::MoreUtils with array of arrays not working
On Jul 9, 2014, at 1:20 PM, Natxo Asenjo wrote: hi, i have an array of arrays which contains equal elements. I would like to isolate the unique values. Do you mean that the subarrays contain equal NUMBERS of elements? I have tried using the uniq method of List::MoreUtils but it apparently does not work with an AoA. That is true. List::MoreUtils::uniq expects a list of scalars (actually, all lists are lists of scalars). The function cannot figure out that the scalars in the list you have passed to it are actually references to other lists. This is what I tried: for my $i ( @$data_ref ) { push $seen_ref, [ $i-{'value1'}, $i-{'value2'}, $i-{'value3'}, $i-{'value4'}, ]; } my @unique = uniq $seen_ref; But unfortunately it does not work. How could I achieve this? If you want to find out the unique values in any collection, insert those values as keys in a hash. Since keys in a hash are unique, when you are done inserting, the keys of the hash will be the unique values from your collection. It doesn't matter what values you insert in the hash to go along with your keys. You are only interested in the keys. However, one common method would be to increment the hash value each time you insert a key. That way, when you are done, you will have a count of the number of times each value appears in your original collection: $hash{$key}++; where $key takes on each of the values in your original collection. Try to implement that scheme, and post your code here if you have any problems. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: List::MoreUtils with array of arrays not working
On Jul 9, 2014, at 2:58 PM, Natxo Asenjo wrote: On Wed, Jul 9, 2014 at 10:35 PM, Jim Gibson jimsgib...@gmail.com wrote: On Jul 9, 2014, at 1:20 PM, Natxo Asenjo wrote: hi, i have an array of arrays which contains equal elements. I would like to isolate the unique values. Do you mean that the subarrays contain equal NUMBERS of elements? yes, same number of elements but some subarrays are exactly the same as well. like this: $VAR1 = [ [ 'a', 'b', 'c', 'd' ], [ 'a', 'b', 'c', 'd' ], [ 'e', 'f', 'g', 'g' ] ]; So is that 7 unique values (a,b,c,d,e,f,g) or 2 unique values ( (a,b,c,d), (e,f,g,g) )? my %uniq; for my $i ( @$seen_ref ) { $uniq{$i} = (); } If $seen_ref is a reference to an array of arrays, then the elements of @$seen_ref are references to arrays. By using those as keys, you are comparing references and not list elements. In order to use the hash method of determining uniqueness, you must convert your list values to a scalar value based on the content of the lists, not the location or identity of the lists as by using the references to the list. The easiest way to do this is to join the elements of the list into a single string. You need to separate the elements using a character that can not appear in any of the elements of any list. For example, if the ':' character does not appear in any element, you can do this: for my $listref ( @$seen_ref ) { my $key = join(':',@$listref); $hash{$key}++; } The keys of %hash will then represent the unique lists. It helps a lot if you post a complete, short program that illustrates the problem you are having. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: List::MoreUtils with array of arrays not working
On Jul 10, 2014, at 11:50 AM, Natxo Asenjo wrote: On Thu, Jul 10, 2014 at 1:00 AM, Jim Gibson jimsgib...@gmail.com wrote: On Jul 9, 2014, at 2:58 PM, Natxo Asenjo wrote: On Wed, Jul 9, 2014 at 10:35 PM, Jim Gibson jimsgib...@gmail.com wrote: On Jul 9, 2014, at 1:20 PM, Natxo Asenjo wrote: In order to use the hash method of determining uniqueness, you must convert your list values to a scalar value based on the content of the lists, not the location or identity of the lists as by using the references to the list. The easiest way to do this is to join the elements of the list into a single string. You need to separate the elements using a character that can not appear in any of the elements of any list. For example, if the ':' character does not appear in any element, you can do this: for my $listref ( @$seen_ref ) { my $key = join(':',@$listref); $hash{$key}++; } The keys of %hash will then represent the unique lists. yes! This is exactly it!. Perfect. Just another question for the icing on the cake. When using the ++ on the $hash{$key}++ how do I get the number of times every list was seen? My apologies for not seeing the obvious here. Iterate over the hash and print out the keys and the values (see below). It helps a lot if you post a complete, short program that illustrates the problem you are having. yes, maybe I should have posted a link to a pastebin service. The problem in this was that there was no small (less than 100 lines) short program because the data from which the AoA gets created in the first place is coming from a largish _DATA_ piece of text - and that is already trimmed to get a representative piece of the real data. You should just include the program in your message. If it is too long to include, it is probably too long for anybody to look at. Here is a short, self-contained program that illustrates the technique: #!/usr/bin/perl use strict; use warnings; my $seen_ref = [ [qw(a b c d)], [qw( a b c d)], [qw(e f g g)] ]; my %hash; for my $listref ( @$seen_ref ) { my $key = join(':',@$listref); $hash{$key}++; } print Unique lists:\n; for my $key ( keys %hash ) { printf %3d %s\n, $hash{$key}, $key; } 13 lines! -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Date::Parse and strange dates
On Jul 25, 2014, at 9:54 AM, Chris Knipe wrote: Hi All, I have the odd (very rare) case where I am given a date in an incorrect format. I already use Date::Parse to convert the dates to a unix timestamp, and it’s working incredibly well. However, on the rare case that I get incorrect dates, Date::Parse does not like them either and errors out. The formats in question that I can’t parse basically looks like Thu, 23 Oct 2008 12:06:48+0400 Note the lack of a space between the seconds and the timezone. Is there a simple quick way to fix that by means of a regex? The simplest way to fix that particular error might be this regex: s/(\d)([+-])/$1 $2/ -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Suddenly this script is not working!
On Jul 28, 2014, at 3:59 PM, ESChamp esch...@gmail.com wrote: Suddenly, without warning or error messages, the script below is producing null for values of $hfile and $bfile! What are $hfile and $bfile? You don’t show them in your script. You show two arrays: @hfile and @bfile, but those are not the same as the scalar variables $hfile and $bfile. When asking other people for help, it is best to reduce your program down to the shortest version that illustrates your problem. People can help you fix that, and you can then apply the fix to your actual program. In this case, it is impossible to help you with the above stated problem, because the variable about which you are complaining do not exist in your program. If you actually mean @hfile and @bfile, you say that $copy is correct. Are the contents of the file named by $copy also correct? The script begins: #!/usr/bin/perl use Tie::File; use File::Copy 'copy'; use File::Spec; and further down, it has: # Tie it to an array # (my $copy = $htmfile) =~ s/(\.htm)\z/-Copy$1/i; copy $htmfile, $copy; tie my @hfile, 'Tie::File', $copy; tie my @bfile, 'Tie::File', $recapfile; ## hfile is the array of the lines of htmfile # print $copy \n; print hfile: 1--$hfile-- \n; $copy's value is correct. I'm on a Windows 7 machine. Should I have the Windows full pathname for perl.exe at the top No, because if you are getting any output at all from your Perl program, then the program has been found and executed by the operating system. Happy to send the entire script to anyone who would like to see it. Produce a shorter version of the script that demonstrates the problem and post it here for all to see. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Suddenly this script is not working!
On Jul 29, 2014, at 5:12 PM, ESChamp esch...@gmail.com wrote: ESChamp wrote on 7/28/2014 6:59 PM: Suddenly, without warning or error messages, the script below is producing null for values of $hfile and $bfile! The script begins: Let me backtrack and provide some background information. This script processes two files, recapfile, a plain text file, and copy, and HTML-formatted file. It reads copy into an array, and recapfile into another array. Then it writes a new array which contains all the initial lines of the recapfile array from the first line down to but not including the first line containing / RESULTS OF BOARD 1/ Most of that information is superfluous. You need to concentrate on the precise problem that you are having. And here is where it goes wrong ('No pre found') ($index) = grep $hfile[$_] eq 'pre', 0 .. $#hfile; die 'No pre found' unless $index; I printed hfile using foreach (@hfile) { print $_\n; } and it looks fine! That is, there is a line with only pre on it!!! Perhaps the line containing ‘pre’ contains whitespace characters that you cannot see when you print it. If so, you can replace you exact test with a regular expression: if( grep /pre/ @hfile ) { … } Or maybe pre occurs on the first line, in which case $index will have the value 0, which is treated as false, and your program will die. This is all speculation because you have not provided us with your exact program and data files. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Suddenly this script is not working!
On Jul 29, 2014, at 11:00 PM, ESChamp wrote: Jim Gibson wrote on 7/29/2014 10:08 PM: This is all speculation because you have not provided us with your exact program and data files. I was warned not to post a 3000 line data file and a 150 line program, but if you'd like me to send them to you off-line, I will. The best way to get help in this situation is to reduce your program and data down to about 10 lines each, but still containing the statements that are giving you problems. Then you can post both program and data here, and people will be able to run your exact code and tell you exactly what is going wrong. In the process of extracting the problem areas from your original program you might well fix the problem yourself. Since we don't have the exact code and data, we are all speculating and guessing what might be the cause. Hope you've got your program working by now. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Why Does the Following Not Work?
On Jul 30, 2014, at 1:23 PM, Martin G. McCormick wrote: I thought that one could test for an empty or undefined array against the @arrayname but it looks like doing that always succeeds if it is set with my or our @arrayname. You can test for an empty or an undefined array. Any array in scalar context will evaluate to the number of elements of the array. An 'if' or 'unless' statement will put the testing expression into scalar context, so in the statment 'if(@array)', @array will be evaluated in scalar context. If the array has any elements, even just one that is undef, @array will evaluate to true. There must be something else going on. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Suddenly.... Part 2
On Jul 31, 2014, at 12:02 PM, ESChamp wrote: John W. Krahn wrote on 7/31/2014 3:11 AM: Peter Holsberg wrote: I think I've isolated the section that is not doing what I want. open (FHIN, $recapfile) or die $!; That would be better as: open my $FHIN, '', $recapfile or die Cannot open '$recapfile' because: $!; Thanks, John. As this is a beginners list and I'm an elderly beginner who is an occasional perl user, what makes that better? It is better because 1) it uses the three-argument form of open instead of the two-argument version (the two-argument version has known risks), 2) it doesn't put the variable containing the file name in superfluous double-quotes, 3) it adds the file name to the error message, and 4) it uses a local lexical variable instead of a global bareword package variable. my $indexb; ## for the recapfile array my $ofile; You never use this variable, it should be: my @ofile; Could you kindly explain that? You are declaring a scalar variable $ofile, but in your code below you use the array variable @ofile. These are not the same thing. If you put 'use strict;' at the beginning of your program, Perl will inform you that you have not declared @ofile. # Create new array containing all the lines of recapfile up to # the string RESULTS OF BOARD 1 XYZZY: while (FHIN) { last XYZZY if / RESULTS OF BOARD 1/; chomp; $ofile[$indexb++] .= $_; That would be better as: push @ofile, $_; } close FHIN; Exactly what lines would yours replace? Why would that be better? push @file, $_; replaces $ofile[$indexb++] .= $_; This is better because 1) it is simpler and therefore less likely to contain an error, 2) uses a Perl built-in function instead of hand-crafted code, 3) doesn't use an additional variable ($indexb), 4) doesn't use the unnecessary concatenation operator '.=' where a simple assignment '=' would do. x .= y is equivalent to x = x . y While this works in your case because the elements of @ofile are all undefined, and concatenating a string to an undefined value results in a simple assignment, it is a superfluous operation. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: What's wrong with this program?
On Aug 6, 2014, at 10:55 AM, ESChamp wrote: The program begins #!/usr/bin/perl You really should add these two lines: use strict; use warnings; here and correct the mistakes they reveal. use Tie::File; use File::Copy 'copy'; use File::Spec; my $copy=00-copy.htm; my $recapfile=00recap.txt; my $htmfile=00.htm; my $ct; tie my @bfile, 'Tie::File', $recapfile or die cannot tie recapfile and bfile $!; tie my @hfile, 'Tie::File', $copy or die cannot tie copy and hfile $!; ## hfile is the array of the lines of htmfile # print $copy \n; print hfile: --$hfile-- \n; print bfile: --$bfile-- \n; You are printing $hfile and $bfile, which are separate variables from @hfile and @bfile and are undefined. You should print $#hfile and $#bfile here instead, which will show you the largest indices of the two arrays. for ($ct = 0; $ct $#hfile; $ct++){ You probably want '$ct = $#hfile' as your condition here, since $#hfile is the greatest index of @hfile and not the number of elements, so your loop will not print the last element of @hfile. print $hfile[$ct] \n; } The output looks like this 00-copy.htm hfile: bfile: You can also use these to print the contents of an array: print @hfile; print for @hfile; for ( @hfile ) { print; } I thought that $recapfile would be tied to @bfile and $copy to @hfile. That is, that each line of $recapfile would become an element of the bfile array, etc. What have I done wrong? Nothing major. Your program should work (with a few minor bugs). Are you sure there is data in 00-copy.htm? -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Embed perl interpreter and call C function from perl?
On Aug 19, 2014, at 9:12 AM, Manuel Reimer wrote: Hello, there are many very good examples on how to execute perl code from C. For example the following tutorial is very helpful: http://perldoc.perl.org/perlembed.html But it only shows calling from C to perl. What I want to do is to create a function in C code and somehow export it to my embedded perl interpreter. Then I want to be able to call this C function from perl code. Can someone point me to a good example on how to do this? Thank you very much in advance. Greetings, Manuel Calling a C program from Perl can be done with the XS mechanism. XS stands for eXternal Subroutine, and is the most common way to provide Perl-to-C linkage. However, you may need to learn something about Perl internals. There is a tutorial about XS at the same website (or via the perldoc command-line program): http://perldoc.perl.org/perlxstut.html Good luck! -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: returning arrays (was: Re: return the list content)
On Sep 8, 2014, at 3:13 PM, lee wrote: Shawn H Corey shawnhco...@gmail.com writes: On Mon, 18 Aug 2014 16:17:53 +0800 Ken Peng o...@dnsbed.com wrote: sub myfunc { my @x=(1,2,3); return \@x; } # or, sub myfunc { my @x=(1,2,3); return [@x]; } # or sub myfunc { return [ 1, 2, 3 ]; } Is there a difference to sub myfunc { return ( 1, 2, 3 ); } The first example returns [ 1, 2, 3 ], which is a reference to a list with 3 elements. References are scalars. The second example returns ( 1, 2, 3 ), which is a list with 3 elements. So, yes, there is a difference. ? And my understanding was/is that in sub myfunc { my @x=(1,2,3); return \@x; } a reference would be returned to an array that ceases to exist when the function returning it has finished. At the point the function returns to, there isn't anything left the reference could refer to. Or is there? Perl will not garbage-collect an element if there is a reference to it. So while the array name @x no longer is in scope once the subroutine has returned, the list that was the value of @x still exists in memory, and the reference returned by the subroutine will be valid. If the reference is not saved or copied, then the list will eventually get garbage collected. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: returning arrays
On Sep 9, 2014, at 2:09 PM, lee wrote: Jim Gibson jimsgib...@gmail.com writes: On Sep 8, 2014, at 3:13 PM, lee wrote: Shawn H Corey shawnhco...@gmail.com writes: On Mon, 18 Aug 2014 16:17:53 +0800 # or sub myfunc { return [ 1, 2, 3 ]; } Is there a difference to sub myfunc { return ( 1, 2, 3 ); } The first example returns [ 1, 2, 3 ], which is a reference to a list with 3 elements. References are scalars. The second example returns ( 1, 2, 3 ), which is a list with 3 elements. So, yes, there is a difference. Hm, so what way of thinking is behind this, and how do you declare an array? Perls 1-4 (I believe) did not have references. They were added with Perl 5, which allowed complex data structures not possible without them. Think array of arrays and hashes of hashes. Once references were introduced, a lot of new possibilities for passing arguments and returning values arose. my $i = 1; my $f = 2.5; my $s = 'string'; my $list = (1, 2, 3); That should be: my @list = ( 1, 2, 3 ); Some people make a distinction between 'list' and 'array'. A list is a sequence of scalar values indexed by an integer. An array is a variable whose value is a list (or something like that -- I don't really distinguish the two myself.) my $list_reference = [(1, 2, 3)]; That can be expressed more simply: my $list_reference = [ 1, 2, 3 ]; my $dereferenced_list = $@list_reference; That is incorrect. You probably mean either this: my @dereferenced_list = @$list_reference; or this: my $list_reference = \@list; or even this: my $list_reference = \(1, 2, 3); my @artificial_array = $@list_reference; There is nothing artificial about that array: my @array = @$list_reference; my @true_array = ? my @true_array = ( 1, 2, 3 ); In either case, the result is the same. @array and @true_array are both arrays with a set of values. I'm finding this very confusing. What's the benefit of using extra designators for some types of variables (arrays) while not even having any at all for some others (lists)? The designators are for named variables. Lists are like pure values, just like 1.0 and string, Like all literal values, they do not need designators (names). Perl will not garbage-collect an element if there is a reference to it. So while the array name @x no longer is in scope once the subroutine has returned, the list that was the value of @x still exists in memory, and the reference returned by the subroutine will be valid. If the reference is not saved or copied, then the list will eventually get garbage collected. Hmm, ok, strange ... good to know, though. Not strange at all. If Perl knows there is no way to reference or access a value in memory, that value will get garbage collected. If there is a way, it won't. To do otherwise would either 1) leak memory, or 2) lead to invalid references. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: returning arrays
On Sep 9, 2014, at 2:57 PM, Shawn H Corey wrote: On Tue, 09 Sep 2014 23:09:52 +0200 lee l...@yun.yagibdah.de wrote: my $i = 1; my $f = 2.5; my $s = 'string'; my $list = (1, 2, 3); No, the count of items in the list gets stored in $list: $list == 3 Unless the thing on the right-hand-side of the assignment is a 'list' and not an 'array'. This is the one place I can think of where the distinction between 'list' and 'array' actually makes a difference. Compare this: my $n = ( 4, 5, 6 ); with this: my @a = ( 4, 5, 6 ); my $n = @a; (Don't try this with the list ( 1, 2, 3 ), either!) -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: share a variable between files
The ‘our’ statement associates a simple name with a package global variable in the current package. Therefore, if you want to make $var in file b.pl mean the package global variable $var in package a ($a:var), just put ‘our $var;’ after the ‘package a;’ statement in file b.pl (see below). On Oct 8, 2014, at 7:35 AM, Hans Ginzel h...@matfyz.cz wrote: Hello! Let's consider following strip-down example: # file a.pl use strict; package a; our $var=1; warn var=$var; # file b.pl use strict; #no strict qw/vars/; require 'b.pl'; package a; our $var; warn var=$var; How to get rid of no strict qw/vars/; to not get message Global symbol $var requires explicit package name at b.pl, please? There is a package specification (package a;) in the b.pl file. Generally, I want to add a key to a global class hash variable (%opt) declared with our in a class module from another file. I realised, that there is possible without warning to define a subroutine in another package, but not to use a global variable from that package (=namespace). -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: use perl format data
On Feb 5, 2015, at 6:53 PM, Wang, Zeng-Sheng (TS-GSD-China-ZZ) zengsheng.w...@hp.com wrote: Dear Uri, First thanks for your kindly help and a read-friendly instruction, I will not use $a and $b for variables. According to your explanation, I finish the code as below: #!/usr/bin/perl -w 2 use strict; 3 open(FH,'',file1); 4 my @first_file = FH; 5 close (FH); 6 7 open(FH,'',file2); 8 my @second_file = FH; 9 close (FH); 10 11 open(FH,'',file3); 12 my @third_file = FH; 13 close (FH); 14 15 chomp @first_file; 16 chomp @second_file; 17 chomp @third_file; 18 19 my ($out_line,$number); 20 $number = @first_file; 21 $out_line=''; 22 for(0..$number){ 23 $out_line.= shift @first_file; 24 $out_line.= \t.shift @second_file; 25 $out_line.=\t.shift @third_file; 26 $out_line.=\n;} 27 28 print $out_line; I realize my target, however, there are some warnings in the prompt, how can I eliminate them? Why? perl format.pl Use of uninitialized value in concatenation (.) or string at format.pl line 23. Use of uninitialized value within @second_file in concatenation (.) or string at format.pl line 24. Use of uninitialized value within @third_file in concatenation (.) or string at format.pl line 25. a b c x y z 1 2 3 d e f q w e n 3 4 5 j p ka s d 8 9 2 1 Thank you very much again. In line 20, @first_file is evaluated in scalar context, which is the number of elements in the array, and assigned to $number. In line 22, your for loop is iterated for values 0 through $number. This results in $number+1 iterations. Therefore, during the last iteration, all of the elements of all three arrays have been exhausted, and your program is attempting to concatenate three undefined values to $out_line. Hence the three warning messages. The easiest way to fix this is to iterate on values (0..$#first_file). $#first_file is the maximum index of the @first_file array. In the longer term, you may want to add logic to your program to handle the case where the files have differing numbers of lines or you have more than three files. There are numerous other improvements you can make to this program, if you are interested. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Using regular expressions to populate a variable?
On Jan 18, 2015, at 9:03 AM, Mike ekimduna...@gmail.com wrote: I was able to find match extraction in the perldoc. Here is a snippet of what I have. my $insult = ( $mech-text =~ m/Insulter\ (.*)\ Taken/ ); print $insult\n; But $insult is being populated with: 1 It should be populated with text. Can anyone tell me what I'm doing wrong here? Your error is assigning the return value of the regular expression in a scalar context. In scalar context, a regular expression returns true or false indicating a match (or not). In array context, however, it returns the captured subexpressions as a list. Try forcing the assignment into array context: my( $insult ) = ( $mech-text =~ m/Insulter\ (.*)\ Taken/ ); You can also use the capture variables $1, $2, $3, etc., which will contain the captured subexpressions: my $insult; if( $mech-text =~ m/Insulter\ (.*)\ Taken/ ) ) { $insult = $1; } -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Eclipse - How do I get back to the first splash screen
On Mar 13, 2015, at 2:07 PM, Sherman Willden sherman.will...@gmail.com wrote: I downloaded Eclipse and I was looking at the screens and in general just messing with Eclipse. Now I can't find the first splash screen with the tutorials, samples, and such. Also is there a help button on Eclipse? It has been awhile since I first downloaded and installed Eclipse, but in the version (Indigo) I have on my system, the Help - Welcome menu item gets you to that initial splash screen with Overview, Samples, Tutorials, and What’s New. As far as a Help button, there is a Help menu. Does that have what you are looking for? -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: How to sort a file based on numerical values exists in each line
On Mar 24, 2015, at 3:42 AM, Anirban Adhikary anirban.adhik...@gmail.com wrote: Hi List I have a file like this. RXMOI:MO=RXOTRX-473-0,SC=0,DCP1=178,SIG=SCCONC,DCP2=179186,TEI=0; RXMOI:MO=RXOTRX-473-5,SC=0,DCP1=223,SIG=SCCONC,DCP2=224231,TEI=5; RXMOI:MO=RXOTRX-473-1,SC=0,DCP1=187,SIG=SCCONC,DCP2=188195,TEI=1; ... This file is from a testing environment. But in production environment this file can be more than 500 lines. So my goal is to sort the file based on the bold numbers and create a new file. This is required for data validation. If the file is not in sorted order then it will be very difficult to validate the file manually. This is a typical application of a technique called a Schwartzian Transform (google it). You can combine all of the steps of extracting the keys and original line into an anonymous array, sorting the array references, and extracting the original line into one command: #!/usr/bin/perl use strict; use warnings; my @lines = DATA; my @sorted = map { $_-[2] } sort { $a-[0] = $b-[0] or $a-[1] = $b-[1] } map { [ /RXMOI:MO=RXOTRX-(\d+)-(\d+)/, $_ ] } @lines; print for @sorted; __DATA__ RXMOI:MO=RXOTRX-473-0,SC=0,DCP1=178,SIG=SCCONC,DCP2=179186,TEI=0; RXMOI:MO=RXOTRX-473-5,SC=0,DCP1=223,SIG=SCCONC,DCP2=224231,TEI=5; RXMOI:MO=RXOTRX-473-1,SC=0,DCP1=187,SIG=SCCONC,DCP2=188195,TEI=1; RXMOI:MO=RXOTRX-1-8,SC=0,DCP1=250,SIG=SCCONC,DCP2=251258,TEI=8; RXMOI:MO=RXOTRX-1-2,SC=0,DCP1=196,SIG=SCCONC,DCP2=197204,TEI=2; RXMOI:MO=RXOTRX-1-0,SC=0,DCP1=178,SIG=SCCONC,DCP2=179186,TEI=0; RXMOI:MO=RXOTRX-460-9,SC=0,DCP1=259,SIG=SCCONC,DCP2=260267,TEI=9; RXMOI:MO=RXOTRX-460-4,SC=0,DCP1=214,SIG=SCCONC,DCP2=215222,TEI=4; RXMOI:MO=RXOTRX-460-8,SC=0,DCP1=250,SIG=SCCONC,DCP2=251258,TEI=8; -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: How to sort a file based on numerical values exists in each line
On Mar 24, 2015, at 7:27 AM, Anirban Adhikary anirban.adhik...@gmail.com wrote: Hi Jim In your code there is some hard coded value [ /RXMOI:MO=RXOTRX But I can't put any hard coded value since I use this code as a function and pass the filename as an argument. As you can see in my code there is no hard coded value. You can modify the regular expression used to extract the sort values depending upon the circumstances under which your function will be used. I was just giving an example of how to combine all of the individual steps into one command. I based the regex I used on the sample data you had provided. If you have any lines that do not match the regular expression, then the method I showed will produce errors, as there will be no extracted values to sort on for those lines. If I were writing a general purpose function, then I would not combine the steps as I have shown, but keep them as separate functions with any necessary error-checking and ilne filtering. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Spliting and creating small files from a main files based on line number
On Mar 25, 2015, at 10:07 AM, Anirban Adhikary anirban.adhik...@gmail.com wrote: Hi List I have a configuration file and I would like to split the main file into multiple small files and push the small temp. files into an array. My config file looks like this GRC01;8;8;1;1;323U6_SIU-8;2048;2048;20;0;OFF (30 lines snipped) GRC01;335;335;32;32;335U6_SIU-335;2048;2048;20;0;OFF This config file has got 32 lines so I am planning to write a code which will create four tmp. files out of the main config file. I have written the following code. #!/usr/bin/perl use Tie::File; use strict; use warnings; my @config_file_contents; tie @config_file_contents, 'Tie::File', GRC01_TG_SCGR_IPM_LIST ###-- This is main config file or die Can't open filename; my @tmp_config_array=@config_file_contents; untie @config_file_contents; my $last_element_index = $#tmp_config_array; my $counter = 1; my $start_index = 0; my $next_index = 8; for (my $i=0; $i= $last_element_index; $i++) { You are iterating over all of the lines in the configuration file, which is 32. I think you only want to execute this loop four times, one for each subfile. print inside for loop\n; print START=$start_index\n; print NEXT=$next_index\n; my $file_to_write = GRC01_TG_SCGR_IPM_LIST_$counter; my @tmp_line_content = splice (@tmp_config_array,$start_index,$next_index); open my $WFH,'',$file_to_write; foreach my $el (@tmp_line_content) { print EL=[$el]\n; next if /^\s*$/; print $WFH $el\n; } close($WFH); $start_index = ($next_index+1); $next_index = ($start_index+8); $i = $start_index; $counter++; # @tmp_line_content = undef; } while executing the code 4 tmp files are created but all of them are zero byte. Though in the print for first time EL I am getting 8 lines and second time EL prints 15 lines but line number 9-15 are skipped.Second time EL should start printing from line number 9 instead it starts printing from line number 18. But the counters like $start_index,$next_index are incrementing properly. Also I am getting warning message splice() offset past end of array at ./tie_file.pl line 22” After the first four iterations of your outer loop, $start_index will be beyond the last element index in @tmp_config_array, and @tmp_line_content will be empty. That is why your subfiles have zero bytes. The subfiles may be correct after the first four iterations, but they are getting overwritten in the subsequent 28 iterations. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Good books to study perl interpreter
The best book on Perl (in my opinion) is “Programming Perl, 4th ed.”, Christiansen, foy, Wall, Orwant. See “perldoc perlbook” for other recommendations, as well as http://books.perl.org On Mar 30, 2015, at 9:42 AM, rakesh sharma rakeshsharm...@hotmail.com wrote: Hi all Please suggest nice books to know perl interpreter. In depth books is that i am looking for. Thanks Rakesh -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: OTRS module
On Mar 26, 2015, at 3:54 PM, Benjamin Fernandis benjo11...@gmail.com wrote: Hi, We are using otrs help desk system which is in fully perl. We require to append automatic comment when our specific customer raise ticket to us. We have iteam no for each customer.So when customer send mail and in body he mentioned iteam code ( like 4322) , so otrs automatically checks sender email id and then fetch iteam code from body and according to that otrs fetch respective information from database or excel sheet and add comment to that ticket. I can write logic out side of otrs. but i never tried to write any module for 3rd party applications. Can you please suggest me a way to do this. Thanks Ben You don’t mention which OTRS Help Desk system you are using, but a Google search turns up this one: https://otrs.github.io/doc/manual/admin/stable/en/html/otrs.html Is that the one? Perl modules are installed as source code files, so you can modify the module’s source and add whatever functionality you need. The OTRS Help Desk looks like a fairly complicated system, so adding functionality without breaking it could be a significant task. In any case, it is probably outside the scope of a Perl beginner’s list. Good luck. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Changing the structure of a hash
It seems that you are working with a two-dimensional array of numbers, so it is not clear why you are using a hash to store this data instead of an array of arrays. What you seem to be asking for is to generate the transpose of the two-dimensional array. So the simplest approach would be to convert your hash into an array of arrays and calculate the transponse. Does that work for you? On Jun 17, 2015, at 10:48 AM, Anirban Adhikary anirban.adhik...@gmail.com wrote: Hi List I have a hash with the following data structure. KEY=[0]-- VALUE=[57 147 237 327 417 507 597 687 777 867 957 1047 1137 1227 1317 1407] KEY=[1]-- VALUE=[58 148 238 328 418 508 598 688 778 868 958 1048 1138 1228 1318 1408] KEY=[10]--VALUE=[67 157 247 337 427 517 607 697 787 877 967 1057 1147 1237 1327 1417] … Now you can see that for first key i.e. KEY 0 the values are from 57 to 1407. But my target is to create another hash whose first key will be KEY0 but its value will be from 57 to 66 that means for each value each column will be changed as each row. How to implement this. Please provide some hints. Best Regards Anirban. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Fire and forget subs
On Jul 6, 2015, at 9:43 AM, Unknown User knowsuperunkn...@gmail.com wrote: What is a good way to fire and forget a sub from a module in perl, in a non blocking mode, preferably without forking or using threads. I may have to run the sub a few times to determine the approx delay for it to run, so i suppose i need a blocking mode for it too. But afterwards, it can run in non blocking mode. - Unknown There is no way to call a subroutine and have it return immediately yet still do productive work in the background without using some sort of multi-tasking, i.e., forks or threads, on a single, normal computer. Starting a separate process using fork is relatively easy. The problem is figuring out when the forked process is done and getting information back from it to the main program. See ‘perldoc perlipc’ for ideas on creating and communicating with separate processes. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: reading from socket
On Aug 11, 2015, at 3:16 PM, Chris Knipe sav...@savage.za.org wrote: Lastly, you're reading from a socket so there's no guarantee that the buffer string is going to necessarily end at the termination boundary. Perhaps the protocol guarantees that, but the socket surely doesn't. You may need to look for that terminating sequence in the middle of the buffer. But isn't that exactly why we set things like autoflush(1) or $|=1? After the data stream has been sent from the server (i.e. CRLF.CRLF) the server stops transmitting data and waits for the next command, so there's no chance that a second data stream may be received by the client socket, at least not until the client socket issues a new command. The TCP transmission protocol is not line-oriented, so, depending upon how the remote node has their socket configured, each buffer of data from the server could possibly contain multiple lines and may not end with a complete line. The packet containing the end of the partial line could be delayed or never arrive if the connection is broken. Transmit and receive are asynchronous, so can be going on simultaneously. Your application protocol may require the server to wait for a command from the client before resuming transmission of the next packet, but that is not required by the TCP protocol. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Yenc encoder performance
On Jul 31, 2015, at 4:39 AM, David Emanuel da Costa Santiago deman...@gmail.com wrote: -BEGIN PGP SIGNED MESSAGE- Hash: SHA256 Hello. Thanks for your reply. I remember that i did some performance tests and $string = $string .something had better performance than $string .= “something Those two lines should result in exactly the same machine instructions. They are two different ways of writing the same thing. There should be no difference in perfomance. which matched the results of (link to stack overflow) http://stackoverflow.com/questions/3104493/performance-with-perl-strings That post compares the following 3 ways of forming a long string (see the benchmark program posted by sebthebert): 1. $string = ‘A’ $string .= ‘B’; $string. = ‘C’; 2. $string = ‘A’ . ‘B’ . ‘C’; 3. $string = join(‘’, (‘A’, ‘B’, ‘C’) ); It does not compare $string .= ‘X’ with $string = $string . ‘X’ Write and run your own benchmark comparing those two cases and post your results here. (#2 turns out to be fastest, with #3 a close second) In any case, you probably shouldn’t be worrying about such minor differences in execution speed. Reliability, accuracy, and ease of maintenance are much more important qualities for software to have. Operators such as ‘.=‘ permit shorter source code and fewer chances for errors. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perl multi threading
On Aug 1, 2015, at 1:49 AM, bikram behera jobforbik...@gmail.com wrote: Hi Team, can you tell me about perl multi threading, uses of multi threading with examples. See ‘perldoc perlipc’ for all kinds of information about multi-threading with lots of example code. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: convert linear array to nested structure
On Jul 21, 2015, at 12:40 PM, Simon Reinhardt si...@keinstein.org wrote: Hi Team, is there a ready solution to convert an linear array of hashrefs like this [ {level = 0, value = string1}, {level = 1, value = string2}, {level = 2, value = string3}, {level = 2, value = string4} ] into the nested data structure [ {value = string1, kids = [ {value = string2, kids = [ {value = string3}, {value = string4}]}]}] ? Any pointer appreciated. That is an unique data structure and transformation requirement (as most are), so you are not likely to find an existing set of code to do exactly what you want. However, the transformation should not be too difficult, so you should try to code up something yourself and ask for help if you get stuck or would like to optimize your solution. If I were coding this, I would like to know how complicated the data structure could become. For example, will there be multiple entries at levels 0 and 1, and how sould they be handled? The data structure you have shown is not very efficient in tems of data storage. Is this the actual data structure, or is it part of something more complicated. For exampe, a more efficient use of space would be this, which uses nested arrays instead of hashes: [ [0, “string1], [1, “string2], [2, “string3], [2, “string4] ] -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: How to interpolate a hash in a string
> On Nov 3, 2015, at 2:03 PM, David Emanuel da Costa Santiago >wrote: > > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA256 > > > Hello all. > > I'm trying to interpolate a hash value in a string but i got stuck. > I already tried with eval, without any success… Show us what you tried. > I have two conf files in the form > conf file 1: > option=value > option2=value2 > > conf file 2: > property=propertyValue > property2=propertyValue2 > > I'm loading these files into a hash. But the problem is that i want to > access, for example on conf file 2, properties from conf file 1: > > property3=$HASH{option2} is that literally what appears in file 2? > So i'm getting the hash for conf file 2: > > %PROPERTIES=(property=>"propertyValue", property2=> "propertyValue2", > property3=> "$HASH{option2}" ); > > but what i want is: > %PROPERTIES=(property=>"propertyValue", property2=> "propertyValue2", > property3=> "value2" ); > > > this is how i'm reading the files: > > sub _read_conf_file{ > open my $FH, '<', shift @_; > while(<$FH>){ >chomp; >s/\#.*//; >/(\S+)\s*=\s*(.+)/; >next if (!defined $1 || !defined $2); >$OPTS{$1}=$2; > } > close $FH; > } > > Does anybody knows how to do this? Here is one way parsing each value with a regular expression: #!/usr/local/bin/perl use warnings; use strict; my %file1 = ( A => 'A', B => 'B' ); my %HASH; _read_conf_file(); for my $key ( sort keys %HASH ) { print "$key = $HASH{$key}\n"; } sub _read_conf_file{ open my $FH, '<', shift @_; while(my $line = ) { next if $line =~ /^\s*#/; chomp($line); my( $key, $val ) = split(/=/,$line); next unless defined $val; if( $val =~ m{\$file1\{'(\w+)'\}} ) { $val = eval($val); # you could also use the following line here instead (with some loss of generality) # $val = $file1{$1}; } $HASH{$key}=$val; } } __DATA__ A=$file1{'B'} -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Traversing directory recursively
On Jul 9, 2015, at 8:27 AM, Nagy Tamas (TVI-GmbH) tamas.n...@tvi-gmbh.de wrote: Hi, So I have a better version. But if it goes down in the recursion tree, at the end it goes into infinite loop, because there is no other dir inside the last dir in the tree. At this point it has to step back. But instead of stepping back it goes into infinite loop. Why? sub Traverse { if( opendir(DIR, $dir) ) { my @files = readdir(DIR); closedir(DIR); foreach my $file (@files) { # generate XML here $actualdir = $dir . \\ ; next if (($file eq '.') || ($file eq '..')); print $file; if((-d $actualdir.$file) and ($file !~ /^\.\.?$/) and ($file ne .) and ($file ne ..)) { # make dir branch $newpath = $actualdir.$file; $writer-startTag(Folder, Name = $newpath); Traverse($newpath, $writer); $writer-endTag(Folder); } else { # make file branch $writer-emptyTag(Object, Name = $actualdir.$file); } } } } Tamas It is because you are calling the Traverse() subroutine with two arguments to recurse a directory tree, but you are not using the arguments. Each call to Traverse uses the global $dir variable as the root of the tree, so it will never terminate. You need a statement such as this near the top of your routine: my( $dir, $writer ) = @_; -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: remove from mailing list
> On Nov 26, 2015, at 7:06 AM, Parysatis Sachswrote: > > Hey, > > can you please remove me from the mailing list? > > Thanks! To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: having trouble understanding the built-in Perl sort with regards to mixed numbers and strings
If you want to sort your data numerically, then the data must look like a number. Your data is mixed numerical and alpha data, hence the error message. You first need to extract the numerical parts of your data records and compare just those parts. The first step would be to write a sort routine that extracts the numerical parts of the two key variables $a and $b, e.g., $anum and $bnum, and returns the value of the expression $anum <=> $bnum ( or $bnum <=> $anum if you want to reverse the order). That is not the most efficient way to solve this problem, as you are extracting the numerical parts more often than necessary, but it is a start. Try that and let us know if you want more help. Once you get that working, you can write a Schwartzian transform that will extract the numerical values only once for each record. > On Jun 17, 2016, at 2:41 PM, Kenneth Wolcottwrote: > > On Fri, Jun 17, 2016 at 2:33 PM, Kenneth Wolcott > wrote: >> Hi; >> >> I'm having trouble understanding the built-in Perl sort with regards >> to mixed numbers and strings >> >> I'm looking at http://perldoc.perl.org/functions/sort.html >> >> I have an array that I want to have sorted numerically and descending. >> >> The array is composed of elements that look like the following regex: >> >> ^\d+\t\[a-zA-Z0-9]+$ >> >> I always have "use strict" at the top of my Perl scripts. >> >> If I try: >> >>my @articles = sort {$b <=> $a} @files; >> >> I get error(s)/warning(s) that the data is not numeric. >> >> if I try: >> >> my @articles = sort {$b cmp $a} @files; >> >> I will get numbers sorted as letters, not numerically. >> >> I tried to understand the sort perldoc page further down, but did >> not grok it at all. >> >> What I did as a workaround was to implement my own extremely >> brute-force sort routine, which works, but is very ugly. >> >> Since I have very few elements (perhaps as many as a couple dozen), >> the inefficiency is immaterial. >> >> I'd rather that my code be correct, intuitive and elegant (and efficient). >> >> Thanks, >> Ken Wolcott > > Addendum: > > It appears that when the sequence of digits is the same length in all > instances that the data will be sorted correctly, but when the length > of the sequence of the digits is not the same in the entire data set, > that is when the sort results will be incorrect. > > My most current data with this reverse character sort mechanism works > correctly, but I'd like it to work in all cases. > > -- > To unsubscribe, e-mail: beginners-unsubscr...@perl.org > For additional commands, e-mail: beginners-h...@perl.org > http://learn.perl.org/ -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Counter Help
> On Feb 9, 2016, at 6:08 AM, James Kerwin <jkerwin2...@gmail.com> wrote: > > Afternoon all, > > I have the following problem: > > I have an array containing a list of non-unique strings. eg: > > @array Contains: > > 11_ > 22_ > 33_ > 33_ > 33_ > 44_ > 44_ > 55_ > > What I would like to do is number each element of the array to look as > follows: > > 11_1 > 22_1 > 33_1 > 33_2 > 33_3 > 44_1 > 44_2 > 55_1 > > I have so far tried to use "exists", while loops and all the usual stuff as > it seemed very simple at first. My attempts have mostly focused on equating > the current element of the array with the previous one and asking if they are > equal and then taking action. I just can't get the logic right though. I keep > getting them all numbered sequentially from 1 to 10 or they all end in "_2" > or alternating "_1" and "_2" If anybody could shed even the smallest glimmer > of light on how to solve this I'd be really grateful. You should define a hash with the strings as keys and the number of strings encountered in the array so far as the hash value. You can then add the number to each string as you iterate over the array and increment the hash value count. Jim Gibson j...@gibson.org -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Counter Help
> On Feb 9, 2016, at 6:46 AM, James Kerwinwrote: > > Thank you both very much for your help. I'll investigate this way when I get > home later (I'm a bit wary of hashes because they're weird). Here is a solution using a hash: #!/usr/bin/perl use strict; use warnings; my @array = qw{ 11_ 22_ 22_ 33_ 33_ 33_ 44_ 44_ 55_ }; my %count; for my $element ( @array ) { $element .= ++$count{$element}; } print "Array:\n\n ". join("\n ",@array) . "\n”; __END__ Note that the array needn’t be sorted for this method to work. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Storing Output file.
> On Jan 28, 2016, at 1:37 AM, Frank Larry <frankylarry2...@gmail.com> wrote: > > Hi Team, > > could you please let me? i have a file which contains "Debug", i would like > to replace debug to "Error", when i ran the below program the out showing > Error message but how to save the output with new changes. Could you please > tell me how to fix it? The way to do this within a larger Perl program is to open a new output file, copy all of the possibly-modified lines to this file. Then you can rename the new file to the same name as the old file, and perhaps rename the old file as well and keep it around as a backup. > > open(FILE, "<filter.txt") or die "Can’t open $!\n”; The three-argument version of open is preferred here, and let’s put the file name in a variable and use a lexical variable for the file handle (untested): my $filename = ‘filter.txt’; open( my $in, ‘<‘, $filename ) or die(“Can’t open $filename for reading: $!”); # create a new file my $newfile = $filename . ‘.new’; open( my $out, ‘>’, $newfile ) or die(“Can’t create $newfile: $!”); > > while($line = ){ while( $line = <$in> ) { > >print "Before substituting: ", $line ,"\n"; > $line =~ s/Debug/Error/g; > print "After substituting : ", $line , "\n”; print $out $line; > > } > > close(FILE); close($in); close($out) or die(“Error writing to output file $newfile: $!”); # rename the old file my $savefile = $filename . ‘.sav’; rename $filename, $savefile; # rename the new file rename $newfile, $filename; Jim Gibson j...@gibson.org -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Script to fork, send data to parent via a tcp conn
> On May 15, 2016, at 5:05 AM, Unknown Userwrote: > > The port is not in use before i run the script. It is in use when i > run it. However the problem is that only one iteration runs. I > expected all to run. Your ‘listen’ statement is in a loop. Therefore, the second time through the loop, the socket will be busy. As Uri suggested, you need to do the listen before the loop so you only do it once. Each iteration of the loop should fork, and the child branch should connect to the socket created by the parent process. The parent branch should do nothing in the loop. At some point, you will want to start waiting for the child branches to end and not exit the program until they have all completed running. See ‘perldoc perlipc’ for examples of parent and children processes communicating through a socket. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: perl for machine learning
> On Feb 7, 2017, at 5:47 PM, community tech <commun...@dnsbed.com> wrote: > > Is there a popular perl library/framework for machine learning? > > Thanks. Have you tried searching the web for “perl machine learning”? Some links from a Google search: <http://www.perlmonks.org/?node_id=638391> <http://search.cpan.org/~kwilliams/Algorithm-SVMLight/lib/Algorithm/SVMLight.pm> <https://www.youtube.com/watch?v=Cdcx4lbUbes> Jim Gibson -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: How to pass all `dig` arguments to Net::DNS?
> On Jan 20, 2017, at 12:24 PM, al...@myfastmail.com wrote: > > For my domain, I retrieve its DNS A-records from a local nameserver using > > /usr/bin/dig -t A @192.0.2.1 -k /etc/named/keys/T.key +noadditional > +dnssec +multiline +norecurs example.com > > In my perl script, I can do the same using system() > > system( "/usr/bin/dig", "-t", "A", "\@192.0.2.1", "-k", > "/etc/named/keys/T.key", "+noadditional", "+multiline", "+norecurs", > "example.com" ); > > which lists all the keys to console. > > I want to get at the same info using Perl, with the results in objects that I > can extract data from and assign to variables. > > IIUC, Net::DNS is the right tool. > > Reading the docs I don't understand how I'd pass all those bind dig-specific > arguments to Net::DNS. > > What's the right syntax / usage for that query in Net::DNS? You need to look at the documentation for the Net::DNS::Resolver, Net::DNS::Packet, and Net::DNS::Question modules as well as Net::DNS. I have not used these modules before, but from the documentation I can suggest something like this to get started: __CODE__ use strict; use warnings; use Net::DNS; my $url = 'www.google.com'; my $resolver = new Net::DNS::Resolver( nameservers => [ ‘192.0.2.1' ], recurse => 0, ); my $reply = $resolver->query($url) or die("Can't resolve $url $!"); my @question = $reply->question; print "Reply:\n"; $reply->print; __END__ It is possible that the Net::DNS family of modules do not support all of the options that the dig program does, but you will have to dig through the documentation and figure that out. For example, you can print out individual sections like this: print "\n;; HEADER SECTION\n"; $reply->header->print(); but I don’t see anything that supports an optional TSIG file equivalent to the -k option (I don’t know what that is, so can’t help with that). Good luck! Jim Gibson -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: newbie question for parsing incoming mails
On Feb 15, 2017, at 7:10 PM, Eko Budihartowrote: > > Jim, > if I want to extract all incoming emails from my qmail emails, how can > specify the folder location and specify the file name since the file name > always different? > > Thx. Use File::Find or opendir and readdir to find all of the emails in a directory tree. You need to figure out the parent directory, if there is one, of the local storage for your email client. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: newbie question for parsing incoming mails
> On Feb 15, 2017, at 8:10 PM, Eko Budihartowrote: > > dear Jim, > I tried to add lines to read file like this: > > use Email::MIME; > > my $file = '/var/qmail/mailnames/ name>/support/Maildir/cur/1487041394.M984019P23084V0803I00E03878.ABCD.NET,S=3987:2,'; > open my $ifh, '<', $file > or die "Cannot open '$file' for reading: $!"; > local $/ = ''; > my $contents = <$ifh>; > close( $ifh ); > > my $mime = Email::MIME->($contents); —> line 13 > > my @parts = $mime->parts(); > > for my $npart ( 0..$#parts ) { > my $part = $parts[$npart]; > my $header = $part->header_obj(); > my $htext = $header->as_string(); > my $body = $part->body(); > > print $header; > } > > after I ran its from CLI, I got an error message Undefined subroutine > ::MIME called at line 13. > > what does the error mean? That means I mistyped the line. It should be this: my $mime = Email::MIME->new($contents); -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: warnings in Math::Complex
> On Feb 9, 2017, at 7:39 AM, Simon Bauerwrote: > > Hi, > > when I turn on -W in one of my perl scripts then I get a lot of warnings > concerning Math::Complex > > Prototype mismatch: sub Math::Complex::abs (_) vs none at > /usr/share/perl/5.22/Math/Complex.pm line 667. > Prototype mismatch: sub Math::Complex::sqrt (_) vs none at > /usr/share/perl/5.22/Math/Complex.pm line 718. > Prototype mismatch: sub Math::Complex::exp (_) vs none at > /usr/share/perl/5.22/Math/Complex.pm line 849. > Prototype mismatch: sub Math::Complex::log (_) vs none at > /usr/share/perl/5.22/Math/Complex.pm line 888. > Prototype mismatch: sub Math::Complex::cos (_) vs none at > /usr/share/perl/5.22/Math/Complex.pm line 935. > Prototype mismatch: sub Math::Complex::sin (_) vs none at > /usr/share/perl/5.22/Math/Complex.pm line 952. Put the following in your Perl program to turn on warnings in the enclosing block only (i.e., just your program and not external modules): use warnings; See the following for more information: perldoc warnings perldoc perllexwarn -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: newbie question for parsing incoming mails
> On Feb 15, 2017, at 9:56 PM, Eko Budihartowrote: > > Jim, > I have one a couple more questions. > -. For the header, what if, I just need the subject, the from, and the > recipient, what is the command? I read the manual in the > https://metacpan.org/pod/Email::MIME#header, it does not tell me how to > extract all of those. > -. And then, for the email contents of the body, it just shows Content-Type: > multipart/alternative; boundary=f403045de9521d20cc054874ce1a > instead of the contents of the email body. How to extract it into string > because it is under html format. Please post all questions to the list. There are other people who can answer your questions better than I can. I just parse the text of the email using regular expressions, line by line: my @lines = split(/[\n\r]+/,$text); for( my $i = 0; $i <= $#lines; $i++ ) { my $line = $lines[$i]; print "$i. $line\n" if $xdebug; if( $line =~ m{ \A Subject:\ (.*) \z }x ) { $subject = $1; etc. You can also try to use the Email::MIME::header method: my $from = $mime->header(‘From’): I haven’t used that, but it might be worth trying. Email::MIME is an extension of the Email::Simple class, so you can look at the documentation for that module as well. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: newbie question for parsing incoming mails
> On Feb 14, 2017, at 10:38 PM, Eko Budiharto <eko.budiha...@gmail.com> wrote: > > dear all, > I have a question. > If I would like to parse all incoming mails from my qmail, which perl module > is easy to use? > my qmail emails incoming is /var/qmail/mailnames//support. In > this folder I already have preline in .qmail for piping emails to my perl > script. > And, my perl script what I already have is like this: > > #!/usr/bin/perl -w > > use Mail::Internet; > > my $mail = Mail::Internet->new( [ ] ); > my $headers = $mail->head->header_hashref; > my @subject = @{${$headers}{'Subject'}}; # or otherwsie do it in list context > it works > > print @subject; > > > when I run it, I do not get anything. > > please help. I use Email::MIME to parse email messages. After reading the email file into the variable $text I do this: my $mime = Email::MIME->($text); my @parts = $mime->parts(); for my $npart ( 0..$#parts ) { my $part = $parts[$npart]; my $header = $part->header_obj(); my $htext = $header->as_string(); my $body = $part->body(); … } Jim Gibson -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: calculate within a loop
> On Sep 9, 2016, at 8:54 AM, Nathalie Contewrote: > > Hello, > I have a question about making a calculation within a loop > > I have a hash of hashes > ## > #!/usr/bin/perl > use strict; > use warnings; > > use Data::Dumper qw(Dumper); > > my %grades; > $grades{"Foo "}{1} = 97; > $grades{"Foo "}{2}= 107; > $grades{"Peti "}{1} = 88; > $grades{"Peti "}{3} = 89; > $grades{"Peti "}{4} = 99; > > print Dumper \%grades; > print "\n"; > > foreach my $name ( keys %grades) { > foreach my $subject (sort {$a <=> $b} keys %{ $grades{$name} }) { > print "$name, $subject: $grades{$name}{$subject}\n"; > } > } > > ## > output is > $VAR1 = { > 'Peti ' => { >'4' => 99, >'1' => 88, >'3' => 89 > }, > 'Foo ' => { > '1' => 97, > '2' => 107 > } > }; > > Peti , 1: 88 > Peti , 3: 89 > Peti , 4: 99 > Foo , 1: 97 > Foo , 2: 107 > ### > Now, what I would like to achieve: > I want to make a calculation, in each $name (Peti and Foo), calculate: > for Peti: > first line : no action > second line -(minus) 1st line: > print subject 3-1=2, 89-88=1 > third line - 2nd line: > print subject 4-3=1, 99-89=10 > > for foo: > first line : no action > second line -(minus) 1st line: > print subject 2-1=2, 107-97=10 > For each $name, declare two variables ($prev_subject and $prev_grade below) to hold the subject and grade. These variables will be undefined during the first pass through the inner loop: for my $name ( keys %grades ) { my $nameref = $grades{$name}; # do one hash lookup my( $prev_subject, $prev_grade ); for my $subject ( sort keys %{$nameref} ) { # {$a<=>$b} is the default for sort my $grade = $nameref->{$subject}; if( defined $prev_subject ) { my $subject_delta = $subject = $prev_subject; my $grade_delta = $grade - $prev_grade; print "$name: $subject_delta: $grade_delta\n"; } $prev_subject = $subject; $prev_grade = $grade; } } -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: calculate within a loop
> On Sep 12, 2016, at 6:24 AM, Nathalie Contewrote: > > Dear all, > > Thanks a lot for the codes various people which all work perfectly!! I have > also discover some useful functions (eval and state) which can also be very > helpful for this kind of data. > > In the light of this, my dataset got more complicated, now there are 3 layers > of hashes and I need now to calculate across those hashes for each name, > I have tried to apply some of the code structure which were kindly provided > and worked well for my first question, although as the data structure is now > more complicated and I need to assess the data accross hashes makes it more > complex and I din’t manage to get a solution for this. Again, any help would > be greatly appreciated. > ## > > > > For each $name (100 and 101)- there are 3 levels, x, y and z -Times are 1,3,5 > for all datasets, across x, y and z . You call the second level keys “levels” here, but in your code the variable you use to hold these key values is $subject. What you call “times” here are held in a variable called $values. That is confusing. It is better if your variable names describe what values they hold, e.g. $level, $time. > What needs to be calculated now with this more complex structure, is for > each name, a calculation across the 3 hashes, for the 3 times. > > for 100: > first line : no action > second line : should reflect the difference between time 3 and time 1 across > x,y and z (x3-x1)+(y3-y1)+(z3-z1) > time :3 - 1 =2, > value: calculation: x (value 3(117)-value 1(97) + y (value 3 (89)) - value 1 > (88)) + z (value 3 (97) - value 1 (95)) > total should be : 117-97 + 89-88 +97-95 =13 I think that should be 23, because (117-97) is 20. > third line: should reflect difference between time 5 and time 3 AND time 5 > and time 1 > time : 5-3, and 5-1 > value: calculation: difference between time 5 and time 3 : x (-value5 (107) - > value 3(117)) + y (value5 (99)- value 3 (89)) + z (value 5 (94) - value 3 > (97) ) = -3 total > difference between time 5 and time 1 : x (-value5 (107) - > value 1(97)) + y (value5 (99)- value 1 (88)) + z (value 5 (94) - value 1 (95) > ) = 20 total So it looks like you have a three-level hash of values (grades?) indexed by name (‘100’, ‘101’), level (‘x’, ‘y’, ‘z’), and time (1, 3, 5). For each name you want to iterate over pairs of times and perform calculations done by grouping the grades according to levels. The first thing to notice is that you need to reorganize your hash so you can iterate over names and times. > > ### > my partial code, > #!/usr/local/bin/perl > use strict; > use warnings; > use feature 'state'; > > use Data::Dumper qw(Dumper); > my %hall; > > $hall{"100 "}{'x'}{1} = 97; > $hall{"100 "}{'x'}{3}= 117; > $hall{"100 "}{'x'}{5}= 107; > $hall{"100 "}{'y'}{1} = 88; > $hall{"100 "}{'y'}{3} = 89; > $hall{"100 "}{'y'}{5} = 99; > $hall{"100 "}{'z'}{1} = 95; > $hall{"100 "}{'z'}{3} = 97; > $hall{"100 "}{'z'}{5} = 94; > $hall{"101 "}{'x'}{1} = 197; > $hall{"101 "}{'x'}{3}= 1117; > $hall{"101 "}{'x'}{5}= 1107; > $hall{"101 "}{'y'}{1} = 188; > $hall{"101 "}{'y'}{3} = 189; > $hall{"101 "}{'y'}{5} = 199; > $hall{"101 "}{'z'}{1} = 195; > $hall{"101 "}{'z'}{3} = 197; > $hall{"101 "}{'z'}{5} = 194; > > print Dumper \%hall; > print "\n"; > > foreach my $name ( sort keys %hall) { > print "name.$name\n"; > foreach my $subject (sort keys %{ $hall{$name} }) { > print "suject.$subject\n"; > > foreach my $values ( sort keys %{ $hall{$name}{$subject}}) { > state ($lgrade,$lsubject,$lname,$ltimes); > >my $grade = $hall{$name}{$subject}; > print "grade is .$grade\n"; # this is not working and gives a reference! %hall has three levels of hashes. So any value of %hall with only two indices will be a reference to a hash. if you want the scalar grade values, you must supply three indices. > my $times = $hall{$name}{$subject}{$values}; > print "time is .$times\n"; > > if (eval { $lgrade and $lname eq $name }) { Why the eval? You can evaluate logical expressions without doing the eval. > > my ( $grade_diff, $times_diff) = ( $grade - $lgrade, > $times-$ltimes); > print "$name, > $grade-$lgrade=$grade_diff:$name,$times-$ltimes=$times_diff \n"; > } > ($ltimes, $lgrade,$lname) = ($times, $grade,$name); > } > } > } Try this: #!/usr/bin/perl use strict; use warnings; my %hall; $hall{"100 "}{'x'}{1} = 97; $hall{"100 "}{'x'}{3} = 117; $hall{"100 "}{'x'}{5} = 107; $hall{"100 "}{'y'}{1} = 88; $hall{"100 "}{'y'}{3} = 89; $hall{"100 "}{'y'}{5} = 99; $hall{"100 "}{'z'}{1} = 95; $hall{"100 "}{'z'}{3} = 97; $hall{"100 "}{'z'}{5} = 94; $hall{"101 "}{'x'}{1} = 197; $hall{"101 "}{'x'}{3} = 1117; $hall{"101 "}{'x'}{5} = 1107; $hall{"101
Re: Perl file exists check
> On Nov 10, 2016, at 3:34 AM, jacekewrote: > > I would like as argument of function use path with special characters then '' > are needed. > That's why function adding apostrophe but after adding apostrofe file cannot > be found. If the string value of the scalar variable that is passed to the subroutine contains special characters, those characters will be used as part of the file path. You do not need to surround the string with single or double quote characters to have those special characters interpreted by the operating system or file system. You will need double-quote characters if you are trying to generate a string value with special characters within the source code of your program as a literal string. > > For me it's strange why after declaration "my $f2 = '/etc/passwd';" paht can > be found but after adding apostrophe like that "$f1 = "'" . $f1 . "'";" paht > cannot be found. That is because the apostrophe characters become part of the path string — not what you want. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perl file exists check
On Nov 10, 2016, at 2:30 AM, jacekewrote: > > Hi, > how can I check if file exist or not ? > > Here's a short test/example: > > if (-e '/etc/passwd') > { > printf "File exist !\n"; > } else { > printf "File not exist !\n"; > } > > That works great ! > > but next a short test/example: > > my $f1 = '/etc/passwd'; > > if (-e $f1) > { > printf "File exist !\n"; > } else { > printf "File not exist !\n"; > } > > and that NOT working ! Why ? > > I use quotes because my path contain special characters. Both of those versions work on my system. There is no reason for the version using a scalar variable holding the file path not to work. Can you post a complete, short, working program that you think does not work? -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perl file exists check
See inline comments below. On Nov 10, 2016, at 3:15 AM, jacekewrote: > > This example will be better : > > #!/usr/bin/perl > use strict; > use File::Basename; > use utf8; > You should indent all blocks (subroutines, if statements, loops, etc.) to make it easier to read and follow the structure of your program. > sub escMe($) { > my $f1 = shift; > my $f2 = '/etc/passwd'; > my $f3 = "'/etc/passwd'"; > my $f4 = '/etc/passwd'; > > $f1 = "'" . $f1 . "’"; This line adds apostrophes at the beginning and end of the file path being passed into the subroutine. You do NOT want to do that! > > if($f1 eq $f2) { > print("Files are same $f1$f2\n"); > } else { > print("Files are NOT same $f1$f2\n"); > } $f1 contains this: ‘/etc/passwd’ $f2 contains this: /etc/passwd One has single quotes and the other does not. They are not the same. Let’s use the constructs q() and qq() for better readability. q(abc) is the same as ‘abc’, and qq(xyz) is the same as “xyz”. qq() allows interpolation of variables and escape sequences, q() does not. > if (-e $f1) > { > printf "File exist $f1 !\n"; > } else { > printf "File not exist $f1 !\n"; > } The file q(‘/etc/passwd’), which has two single-quote characters, one at the beginning and one at the end, does not exist. > > if (-e '$f2') > { > printf "File exist $f2 !\n"; > } else { > printf "File not exist $f2 !\n"; > } You are testing for the existence of a file with the name q($f2). In other words, the file name (or path) has three characters in it: dollar sign, eff, two. That file does not exist (in the current directory). > > if (-e '$f3') > { > printf "File exist $f3 !\n"; > } else { > printf "File not exist $f3 !\n"; > } Same problem. q($f3) does not exist. > > if (-e '$f4') > { > printf "File exist $f4 !\n"; > } else { > printf "File not exist $f4 !\n"; > } Same problem. q($f4) does not exist. > if (-e '/etc/passwd') > { > printf "File exist !\n"; > } else { > printf "File not exist !\n"; > } > The file q(/etc/passwd) does exist. > return $f1; > } > > escMe("/etc/passwd"); > > > > Output: > Files are NOT same '/etc/passwd'/etc/passwd > File not exist '/etc/passwd' ! > File not exist /etc/passwd ! > File not exist '/etc/passwd' ! > File not exist /etc/passwd ! > File exist ! > -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Changing date format using carpout
> On Mar 25, 2017, at 8:51 AM, SSC_perlwrote: > > I’ll sometimes use the following code at the beginning of a script to > log errors while testing: > > BEGIN { > use CGI::Carp qw(carpout); > open(_STDERR,'>'); close STDERR; > open (my $log, '>>', 'logs/error.log') or warn("Couldn't open > error.log: $! \n"); > carpout($log); > close ($log); > } > > However, I would like to change the date format. I’m not wild about > seeing the the full timestamp on every line: > > [Sat Mar 25 08:05:58 2017] > > Is there a way I can format that to my liking? I see there's a > ‘noTimestamp’ option to stop it from printing altogether, but I don’t see a > way to change the output. The timestamp is generated in the stamp() function, which starts on line 387 of the source file Carp.pm. You can copy the source of the modules and edit the stamp function to generate a shorter timestamp. You could also try overriding the supplied function of the imported module with your own version (not sure exactly how that is done). > > Side question: is there a better way to accomplish what I’m doing > above? I’m happy with what I already have (except for the date) but only > because I don’t know anything else. I’d like to hear how others do this. I usually write my own log files using normal file output functions. However, that is harder, but not impossible, when you are writing CGI programs. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Warnings when sorting by hashref
> On Apr 11, 2017, at 6:13 AM, Mike Martin <m...@redtux.org.uk> wrote: > > Hi > > I have the following code as an example against a hash of hashes, to sort by > hashrf key > > foreach my $opt (sort {uc($options{$b}->{type}) cmp uc($options{$a}->{type})} > keys %options){ >my $type=$options{$opt}->{vtype}; >$video_type->append_text($type) if defined($type) ; >} > > The sort function works perfectly, however perl throws up the following > warning for each line > > Use of uninitialized value in uc at > > Any ideas how to get rid of the warning Make sure that all $options{$key}->{type} values are defined: foreach my $key ( keys %options ) { $options{$key}->{type} = ‘’ unless defined $options{$key}->{type}; } Substitute something else for ‘’ depending upon where you want to sort undefined {type} values in your sort order. Jim Gibson -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: How to use Text::Wrap correctly
> On Aug 13, 2017, at 6:02 PM, Harry Putnam <rea...@newsguy.com> wrote: > > My aim: > > Run certain kinds of log file lines thru a perl script that will: > > 1) Identify each line by regex that finds pattern at start of line > 2) When such a line is found, print newline first then > 3) wrap any lines longer than specified number of columns. > > > I was not able to divine from `perldoc Text::Wrap' how to really use > it to do what I want. > > my non-working effort stripped to the bare bones: > > use strict; > use warnings; > use Text::Wrap; > > my $rgx = qr/@{[shift]}/; > > $Text::Wrap::columns = 68; > > my @text; > > while (<>) { > if (/$rgx/) { > print "\n"; > print wrap(",", @text); > } > } > > It wasn't at all clear from perldoc Text::Wrap how @text is supposed > to be populated. @text is a list of scalar strings passed to the wrap subroutine. You can pass a single string also. Try this loop instead: while (<>) { if (/$rgx/) { print "\n"; print wrap(",", $_); } } It is usually better to use explicit variables: while ( my $line = <> ) { if (/$rgx/) { print "\n"; print wrap(",", $line); } } Jim Gibson -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Filehandle within foreach loop
If you wish to terminate execution of a foreach loop without iterating over all of the elements (@files, in this case) use the “last” statement: foreach my $file ( @files ) { # process file open( my $fh, ‘<‘, $file ) or die(…); while( my $line = <$fh> ) { # process line } close ($fh) or die( … ); last if (some_condition); } If you wish to terminate the foreach loop from inside the while loop, you can give the foreach loop a label and use the label in the “last” statement. Without an explicit label, “last” will terminate the innermost loop (the while loop here): ALL: foreach my $file ( @files ) { # process file open( my $fh, ‘<‘, $file ) or die(…); while( my $line = <$fh> ) { # process line last ALL if (some_condition); } close ($fh) or die( … ); } However, in that case you have skipped the close statement, and the close will happen automatically when the file handle $fh goes out of scope, but you cannot do any explicit error checking on the close. > On Jul 12, 2017, at 12:20 PM, perl kamal <kamal.p...@gmail.com> wrote: > > Hello All, > > I would like to read multiple files and process them.But we could read the > first file alone and the rest are skipped from the while loop. Please correct > me where am i missing the logic.Thanks. > > use strict; > use warnings; > my @files=qw(Alpha.txt Beta.txt Gama.txt); > > foreach my $file (@files) > { > open (my $FH, $file) or die "could not open file\n"; > > while( my $line = <$FH> ){ > #[process the lines & hash construction.] > } > close $FH; > } > > Regards, > Kamal. Jim Gibson -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: File::Find report file count per directory
On Jun 28, 2017, at 2:10 PM, Harry Putnam <rea...@newsguy.com> wrote: > > 1) I want to count numeric named files in each directory. > > 2) I want to capture the name of the directory those files are in > > 3) I want to print the directory name and the count (if any) for each > directory. > > I know that all the information I want to extract is available in > File::Find. > > Just having trouble seeing how to get at it when I want it. > > Connecting the directory name with the file count is the rub for me. > > I googled extensively but have not found this specific usage. I get > piles of examples for just counting files throughout a hierarchy. > But not giving a count and directory name of `each' directory. > > I've done several hours of fumbling around and have produced several > abject failures. > > Finally got something that did what I wanted. > > The script below does those three things... But I have a sneaking > feeling there is some easier way to extract the info. Something > simpler that is right in front of me... but escaping me. > > The test directory structure looks like this: > > ls -R dir1 > dir1: > 111 222 333 dir2 > > dir1/dir2: > 111 222 333 dir3 > > dir1/dir2/dir3: > 111 222 333 > > ff1c: > --- --- ---=--- --- --- > > my $usage = > "Purpose: bleh > Usage: bleh > "; > > my $dir; > if (! @ARGV){ > warn "$usage", > "Usage tripped: line: <" . __LINE__ . ">\n", > "We need at least 1 top directory\n"; > exit; > } elsif (@ARGV > 1) { > warn "$usage", > "Usage tripped: line: <" . __LINE__ . ">\n", > "Too many cmdline arguments\n"; > } > > $dir = shift; > if (! -d $dir) { > warn "$usage", > "Usage tripped: line: <" . __LINE__ . ">\n", > "<$dir> not found .. aborting ..\n"; > exit; > } > --- --- ---=--- --- --- > > ff1c out: > >> ./ff1c > > ./dir13 > ./dir1/dir2 3 > ./dir1/dir2/dir3 3 > (9) numeric files overall I don’t see how the code you have posted can possibly produce the output you have reported. The code above looks like error checking that the user of the program has entered one argument, and that argument is the name of a directory. How about posting the rest of your program. The error checking part is the least interesting part, as it is very straightforward and although it is a valuable part of any good program, it is not relevant to the discussion of how to count numerically-named files. So how about posting a program that includes only the part of Perl that you want people to evaluate. If I had to do this, I would create a hash that had the directory name as a key and the number of files in that directory that have a numerical file name. I would use File::Find to traverse the directory tree, check the name of each non-directory file, and increment the count for the enclosing directory for each such file I found. A line something like this: $filecount{$File::Find::dir}++; would be central to my program. Jim Gibson -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: File::Find .. still confused slightly
You have a logic error in your code somewhere. Your logic for counting the files with a name matching a certain pattern is too complicated to follow and point out where your error lies and how to fix it. The basic problem is that your logic depends upon detecting when the directory name changes, and will therefore not work on the last file encountered. It also depends upon all of the files in a directory being scanned sequentially. While that seems to work, it is not guaranteed by File::Find. A simpler method for counting files in each directory would be to use a hash with the directory name as key and the number of files as value. Here is a program for doing that: #!/usr/bin/env perl use strict; use warnings; use File::Find; my $startdir = './dir1'; my %counts; find sub { return unless -f; return unless /^\d+$/; $counts{$File::Find::dir}++; }, $startdir; my( $total_dir, $total_files); print "# Files Directory\n--- ---\n"; for my $dir ( sort keys %counts ) { (my $shortdir = $dir) =~ s{.*News/agent/nntp}{}; my $nfiles = $counts{$dir}; printf "%5d %s\n", $nfiles, $shortdir; $total_dir++; $total_files += $nfiles; } print "\n<$total_files> files in <$total_dir> directories\n”; Note that I recommend keeping the raw numerical data (file counts) and not saving the output lines. Generate the output lines when you print them. Jim Gibson -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: keyboard input without pressing return?
> On May 5, 2017, at 6:06 PM, lee <l...@yagibdah.de> wrote: > > > Hi, > > how can a sleeping program react to a key that was pressed without > return being pressed? > See ‘perldoc -q "How can I read a single character from a file? From the keyboard?” Jim Gibson jgib...@snowlands.org -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: prime factors
> On May 2, 2017, at 7:58 AM, derrick cope <derr...@thecopes.me> wrote: > > I was writing a program to solve the #3 exercise on project Euler. I needed > to find the prime factors of a given number. > I have solved it already but a couple of the ways I tried to solve the > problem caused a problem. Exercise #3 is to find the largest prime factor of the number 600,851,475,143. > > The below worked for smaller numbers but when I used the 12 digit number > given by project Euler I got "Out of memory!" > > chomp( my $factor = <>); > my @primefactor = grep { ( $_ ) } ( grep { $factor % $_ == 0 } > 1..$factor ); Presumably, you have entered the number 600851475143 into the command line that executes your program. Therefore, $factor is equal to 600851475143 and the expression 1..$factor will be a list of 600851475143 elements; ( 1, 2, 3, … , 600851475143 ). You will need a computer with several petabytes of memory to store that list. > > sub isprime { > my $numb = shift; > my @quot = grep { >if ( $numb % $_ == 0 ) {1; >} else { 0;} > } 2..$numb-1; > unless ( @quot ) { >1; >#say "prime"; >} else { >0; >#say "not prime"; >} > } This function also generates a very long list of integers (2..$numb-1). > > > This one worked but caused my computer to crash. > > my $xxx = 1; > while ( $xxx < $factor ) { >if ( $factor % $xxx == 0 and ($xxx) ) { >say $xxx; >} >$xxx++ > } > > what is causing perl to do this? Would using a module save memory? > Thanks for any help. Using a module would not save significant memory. You need to devise an algorithm that does not require long lists of numbers. You need to test each potential prime factor one at a time. You will also need to address the fact that Perl’s integers cannot represent the number 600851475143 in their normal 32- or 64-bit formats. See ‘perldoc bignum’. Also note that the smallest factor of any number cannot be larger than the square root of that number, so the function isprime need not consider potential factors larger than the square root of its argument. Jim Gibson -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: How to use Text::Wrap correctly
> On Aug 18, 2017, at 6:05 AM, Harry Putnam <rea...@newsguy.com> wrote: > > jimsgib...@gmail.com (Jim Gibson) writes: >>> > > A second attempt trying to use your last example as inspiration > follows: > > ---8< snip -8< snip -- > > use strict; > use warnings; > use Text::Wrap; > > my $rgx = qr/@{[shift]}/; > > $Text::Wrap::columns = 68; > > > while ( my $line = <> ) { > if (/$rgx/) { > print "\n"; > print wrap(",", $line); > } > } > > ---8< snip -8< snip -- > > Output from same `logs' file: > > Use of uninitialized value $_ in pattern match (m//) at > /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 1. > Use of uninitialized value $_ in pattern match (m//) at > /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 2. > Use of uninitialized value $_ in pattern match (m//) at > /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 3. > Use of uninitialized value $_ in pattern match (m//) at > /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 4. > Use of uninitialized value $_ in pattern match (m//) at > /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 5. > Use of uninitialized value $_ in pattern match (m//) at > /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 6. > Use of uninitialized value $_ in pattern match (m//) at > /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 7. > Use of uninitialized value $_ in pattern match (m//) at > /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 8. There is an error in what I posted (sorry). The input is read into the $line variable, but your regular expression is implicitly testing the default variable $_. The loop should be: while ( my $line = <> ) { if ( $line =~ /$rgx/ ) { print "\n"; print wrap(",", $line); } } I don’t know what Text::Wrap is complaining about. It helps if you are able to include a text string in your posted source code that demonstrates the problem. Use the built-in DATA file handle to include data within your program source. Check out ‘perldoc perldata’ and search for “__DATA__”. This is the pattern: ... while ( my $line = ) { if ( $line =~ /$rgx/ ) { print "\n"; print wrap(",", $line); } } ... __DATA__ This is data to be read using the operation. Jim Gibson jgib...@snowlands.org -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Questions about CGI
> On Jun 6, 2018, at 2:16 PM, Ahmad Bilal wrote: > > Ok, I went over to previously answered questions under the cgi tag here on > stackoverflow. This message was posted to the Perl Beginners list, so you are not at Stackoverflow any more. > > This seems to be the most voted one: What is Common Gateway Interface (CGI)? > > But it still doesn't clear a few things, which I'm asking here. > > Since RFC3875 is only a informational doc, and there is no finalized standard. > > • Who implements CGI protocol? Who defines its "standard behavior" on > servers such as Apache. The CGI protocol is implemented by web servers and web browsers. It is a way for browsers to query a server and get dynamic information, rather than a static web page. The CGI request is part of the Hypertext Transfer Protocol (HTTP). It allows parameters to be sent by the browser to the server, which then uses the values of these parameters to generate a dynamic web page that it sends back to the browser. > > • How does C files work with CGI in modern environment. Please > elaborate using a "Hello World!" as a response to a form submission. You can write a CGI program in just about any language. Since this is a Perl list, maybe you should be asking about CGI programming in Perl. I have written CGI programs in Perl, but now use PHP (for compatibility with existing CGI scripts). Perl has modules to assist in CGI program development. The oldest of these is the CGI.pm module, but it has now fallen out of favor, and other modules are now recommended. I haven’t used any (or done any CGI programming in Perl for a long time), so I can’t recommend any from personal experience. Check out these pages: <https://metacpan.org/pod/CGI> <https://metacpan.org/pod/Task::Kensho#Task::Kensho::WebDev:-Web-Development> > > > > -- > Ahmad Bilal > Jim Gibson -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/