Re: what is something like this - $seen{$1}
On Tue, 26 Oct 2004 16:50:11 -0400, Bob Showalter [EMAIL PROTECTED] wrote: rs wrote: Hi, Here's a snippet of some code from the cookbook. Hmm, time to get a new cookbook :~) Nope. Just make sure you understand the the OP changed the code quoted from the cookbook, and that the cookbook's code snippets do not use strict in this example. I am trying to understand what $seen{$1} is. ie where did $1 come from, and what is in $seen{$1}, and how is the hash populated? $1 is a built-in variable that is set by capturing parens in a regular expression. It's not being set in the script below, and the script below doesn't properly capture the unique characters. yup. I agree bob! however, if the OP had correctly quoted the book, you'd see it does its job: %seen = ( ); $string = an apple a day; foreach $char (split //, $string) { $seen{$char}++; } print unique chars are: , sort(keys %seen), \n; Also, a couple of paragraphs later, the Cookbook goes on to show how to solve the same problem with a while loop and a regular expression: %seen = ( ); $string = an apple a day; while ($string =~ /(.)/g) { $seen{$1}++; } print unique chars are: , sort(keys %seen), \n; In that example, the parens are grabbing a character and dropping it into $1. Somehow the OP got the two examples mixed up. Hey OP, since we've pointed out the mix-up, does this clear up your question? Or do you still not understand what the two above examples are saying? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: what is something like this - $seen{$1}
%seen = ( ); $string = an apple a day; foreach $char (split //, $string) { $seen{$char}++; } print unique chars are: , sort(keys %seen), \n; Also, a couple of paragraphs later, the Cookbook goes on to show how to solve the same problem with a while loop and a regular expression: %seen = ( ); $string = an apple a day; while ($string =~ /(.)/g) { $seen{$1}++; } print unique chars are: , sort(keys %seen), \n; In that example, the parens are grabbing a character and dropping it into $1. Somehow the OP got the two examples mixed up. Hey OP, since we've pointed out the mix-up, does this clear up your question? Or do you still not understand what the two above examples are saying? I realized I should have added a bit more reference information to the post. For those of you new to the list, OP stands for Original Poster. In this context, I'm talking about and to Radhika. For those of you with or without a copy of the Cookbook we're talking about, I'm referring specifically to the Perl Cookbook, 2nd Edition book written by Tom Christiansen, Nathan Torkington. The code snippets above come from Chapter 1, section 1.6, titled Recipe 1.6 Processing a String One Character at a Time. I hope that helps add some context. -Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: counting gaps in sequence data
On Thu, 14 Oct 2004 16:11:42 -0600, Michael Robeson [EMAIL PROTECTED] wrote: Yeah, I have just submitted that same question verbatim to the bio-perl list. I am still running through some ideas though. I have both Bioinformatics perl books. They are not very effective teaching books. The books spend too much time on using modules. Though while I understand the usefulness of not having to re-write code, it is a bad idea for beginners like me. Because re-writing code at first gives me a lot of practice. Some of the scripts in the books use like 3-5 modules, so it gets confusing on what is going on. I mean the books are not useless, but they definitely are structured for a class with a teacher. :-) -Mike Hi again, Mike! I've thrown together the following code. I have not commented this! If you have some questions, just ask. I hard coded the sequences for my ease-of-use. It looked to me like you have figured out how to grab the sequences out of a file and throw them in a hash. This code uses some deep nested references, and therefore, some crazy dereferences. Have fun with it, I know I did! Things that might look weird: check out perldoc -f split for info on using a null-string to split with (That's were I found it!) and of course perldoc perlref for all the deep nested references and dereferencing stuff! I'm currently reading Learning Perl Objects, References Modules by Randal Schwartz. I highly recommend it. It helped a lot in this exercise. Here's the code: use warnings; use strict; my %sequences = ( 'Human' = acgtt---cgatacg---acgact-t, 'Chimp' = acgtt---cgatacg---acgact-t, 'Mouse' = acgata---acgatcgacgt, ); my %results; foreach my $species( keys %sequences ) { my $is_base_pair_gap = 0; my $base_pair_gap; my $base_pair_gap_pos; my $position = 1; foreach( split( / */, $sequences{$species} )) { if( /-/ ) { unless( $is_base_pair_gap ) { $base_pair_gap_pos = $position; } $is_base_pair_gap = 1; $base_pair_gap .= $_; } elsif( $is_base_pair_gap ) { push @{$results{$species}{length($base_pair_gap)}}, $base_pair_gap_pos; $is_base_pair_gap = 0; $base_pair_gap = undef; } $position++; } } foreach my $species( keys %results ) { print $species:\n; foreach my $base_pair_gap( keys %{$results{$species}} ) { printNumber of $base_pair_gap base pair gaps:\t, scalar( @{$results{$species}{$base_pair_gap}}), \n; print at position(s) , join( ',', @{$results{$species}{$base_pair_gap}} ), .\n; } print \n; } The heart of this code is this line: push @{$results{$species}{length($base_pair_gap)}}, $base_pair_gap_pos; there is a %results hash which has keys that are the different species, and values that point to another hash. THAT hash (the inner hash) has keys that are the length of the base-pair-gaps, and values that point to an array. The array holds a list of the positions of those base-pair gaps! The first base pair gap in the human sequence is '---' at the 6th character. That looks like this (warning: pseudo code for clarity!) %results-{'Human'}-{ 3 }-[6] When we find the second '---' gap, we add it's position to the array: %results-{'Human'}-{ 3 }-[6,16] Then, we find a new base-pair-gap ('-') so we add a new key to inner hash: %results-{'Human'}-{ 3 }-[6,16] -{ 5 }-[25] Next, we move on to the next species ... %results-{'Human'}-{ 3 }-[6,16] -{ 5 }-[25] -{'Mouse'}-{ 3 }-[7] So, finally, with Data::Dumper, we can see the %results hash when the code is done processing the sequence: %results = { 'Human' = { '3' = [ 6, 16 ], '5' = [ 25 ] }, 'Mouse' = { '4' = [ 17 ], '3' = [ 7 ] }, 'Chimp' = { '3' = [ 6, 16 ], '5' = [ 25 ] } }; I hope this is helpful! This really was a lot of fun. --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: counting gaps in sequence data
On Thu, 14 Oct 2004 11:02:06 -0600, Michael Robeson [EMAIL PROTECTED] wrote: I have a set of data that looks something like the following: SNIP So, any suggestions would be greatly appreciated. If anyone can help me out with all or even just bits of this I would greatly appreciate it. This should help me get started on some more advanced parsing I need to do after this. I like to try and figure things out on my own if I can, so even pseudo code would be of great help! -Thanks -Mike Hi Mike, This list works best if you show us some code you have tried and then we can help you troubleshoot it. It lets us know that you've already tried to solve your problem and aren't looking for a free scripting service! Show us some of that code you talked about and we'll help you out --Errin PS: is this a common problem/exercise in some class somewhere? I keep seeing requests for help having to do with those exact strings of DNA data. Is there a bunch of people working on DNA projects using Perl somewhere? Or, is this some homework? -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: counting gaps in sequence data
On Thu, 14 Oct 2004 15:40:24 -0400, Willy West [EMAIL PROTECTED] wrote: PS: is this a common problem/exercise in some class somewhere? I keep seeing requests for help having to do with those exact strings of DNA data. Is there a bunch of people working on DNA projects using Perl somewhere? Or, is this some homework? bio-informatics is a big area in which Perl is involved... there's even a book from O'reilly on the subject... also, a mailing-list is available... from http://lists.perl.org/ - bioperl-announce-l List is for people only interested in announcements of Bioperl code releases, updates and events. bioperl-l Unmoderated list for general discussion of bioperl modules, current future efforts and related topics. - in the latter of the two lists, i counted about 80 messages in the first half of this month. hmm... i might join it... :) might be fun!! -- Willy http://www.hackswell.com/corenth If what you say is true, then maybe Mike needs to take his questions to those list? I mean, if the problem he's describing is common and the data format he's using is common, I bet it's been solved already. Hey mike, have you searched on CPAN (search.cpan.org) for this? -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: counting gaps in sequence data
On Thu, 14 Oct 2004 16:08:44 -0400, Willy West [EMAIL PROTECTED] wrote: On Thu, 14 Oct 2004 14:47:57 -0500, Errin Larsen [EMAIL PROTECTED] wrote: bio-informatics is a big area in which Perl is involved... there's even a book from O'reilly on the subject... If what you say is true, then maybe Mike needs to take his questions to those list? I mean, if the problem he's describing is common and the data format he's using is common, I bet it's been solved already. Hey mike, have you searched on CPAN (search.cpan.org) for this? that might be fine- but his question is fundamentally Perl in nature- he may use the information for bio-informatics, but he is looking for an answer regarding effective Perl use when dealing with strings- that's classic Perl and a classic question for this list :) i wish i could answer his question right off the bat, but i can't :/ awell... very true. I've been playin' with this problem, it seems very fun/interesting. I was thinking this would be alot easier to play with if the characters in the string were all in an array. so I played with the length() function and the substr() function to push them all into an array in a loop. something like this (prolly a prettier/easier way to do this): use Data::Dumper; my $human = acgtt---cgatacg---acgact-t; my @human; for my $pos( 0 .. (length($human) -1)) { push @human, substr($human, $pos, 1); } print Dumper([EMAIL PROTECTED]; The above produces the following output, which I was thinking might be easier to work with for Mike's problem: $VAR1 = [ 'a', 'c', 'g', 't', 't', '-', '-', '-', 'c', 'g', 'a', 't', 'a', 'c', 'g', '-', '-', '-', 'a', 'c', 'g', 'a', 'c', 't', '-', '-', '-', '-', '-', 't' ]; This is kinda fun! --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: counting gaps in sequence data
On Thu, 14 Oct 2004 23:23:48 +0200, Paul Johnson [EMAIL PROTECTED] wrote: On Thu, Oct 14, 2004 at 11:02:06AM -0600, Michael Robeson wrote: I have a set of data that looks something like the following: So, my problem is that I think I know some of the bits of code to put into place the problem is I am getting lost on how to structure it all together. Hi Paul, I think you missed a critical part of Mike's post!: For now I am just trying to get my output to look like this: Human number of 3 base pair gaps: 2 at positions: 6, 16 number of 5 base pair gaps: 1 at positions: 25 Chimp and so on ... I've put together something that will get the first part done (counting base pair gaps, I guess is the point!) Code is as follows: use warnings; use strict; use Data::Dumper; my %sequences = ( 'human' = acgtt---cgatacg---acgact-t, 'chimp' = acgtt---cgatacg---acgact-t, 'mouse' = acgata---acgatcgacgt, ); my %results; foreach my $species( keys %sequences ) { my $base_pair = 0; my $base_pair_value; foreach( split( / */, $sequences{$species} )) { if( /-/ ) { $base_pair = 1; $base_pair_value .= $_; } elsif( $base_pair ) { $results{$species}{length($base_pair_value)} += 1; $base_pair = 0; $base_pair_value = undef; } } } foreach my $species( keys %results ) { print $species = $sequences{$species}\n; foreach my $base_pair( keys %{$results{$species}} ) { printNumber of $base_pair base pair gaps:\t$results{$species}{$base_pair}\n; } } This will produce the following output: # dnatest human = acgtt---cgatacg---acgact-t Number of 3 base pair gaps: 2 Number of 5 base pair gaps: 1 chimp = acgtt---cgatacg---acgact-t Number of 3 base pair gaps: 2 Number of 5 base pair gaps: 1 mouse = acgata---acgatcgacgt Number of 4 base pair gaps: 1 Number of 3 base pair gaps: 1 I put the sequence in the output for easy troubleshooting and checking. I'm still working on figuring out the positional data. This IS fun. I'll post when I've got it figured out --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Email Address Arguments
I figured it out. I thought I'd post what I found. I've cobbled some code together to test stuff out with: #!/usr/bin/perl use warnings; use strict; my @addresses; my @message; if( @ARGV ) { print There are arguments\n; while( $ARGV[0] =~ /[EMAIL PROTECTED]/ ) { The above line of code was the culprit. I added a check to make sure @ARGV wasn't empty and everything worked out. This line looks like this now: while( @ARGV $ARGV[0] =~ /[EMAIL PROTECTED]/ ) { push @addresses, $ARGV[0].', '; shift; } print @addresses\n; } else { print There are no arguments\n; } while( ) { if( /^.$/ ) { last; } else { push @message, $_; } } print \n\nThe following message will be sent:\n; print @message\n; --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Email Address Arguments
Hi Perl Mongers, I'm trying to parse some command line options. I'm expecting either no arguments, email addresses or email addresses and file names/piped input. This script will take the email addresses and send the contents of a file to them, or the output of a piped command. So, I would expect something like this: # ls -la | mailer [EMAIL PROTECTED] [EMAIL PROTECTED] or # ls -la | mailer or # mailer [EMAIL PROTECTED] ls.out so, I can check for no arguments with: if( @ARGV ) { #process args here } and, I can match email addresses with this regex: /[EMAIL PROTECTED]/ I guess I'm asking for help on putting this stuff together. When I get done, I'd like to see a single string with the email addresses in it, separated by commas. I've been trying lots of stuff, but none of it is working. I can't seem to strip off the email addresses from the front of @ARGV without getting hung up when I get to the end, or if there is an (incorrectly) placed argument in the middle of addresses that is NOT an address, like this: # ls -la | mailer [EMAIL PROTECTED] wrong.com [EMAIL PROTECTED] I know I'm just missing something simple. I did think about using one of the getopt()/getopts() modules, but I'd rather not have to use a command-line flag/option to make this all work. Can you guys help me out? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Email Address Arguments
On Tue, 12 Oct 2004 09:26:12 -0600, Wiggins d Anconia [EMAIL PROTECTED] wrote: Hi Perl Mongers, I'm trying to parse some command line options. SNIP So in this case you have two arguments in @ARGV and waiting text on STDIN? Is it this last part that is confusing you. yes ... I'll explain below SNIP and, I can match email addresses with this regex: /[EMAIL PROTECTED]/ Well you can start to match email addresses. It is better to match them with Email::Valid once you have what you think is an address. Yes ... I'm just not to the point where I'm making this pretty yet, need to parse the arguments first and the above (dirty) regex works for this purpose. I guess I'm asking for help on putting this stuff together. When I SNIP What have you tried? Where did you fail? You know better than to post without code :-). I know, I know. I just was having a brain-empty kinda morning. I couldn't kick-start the thinking! SNIP So it goes something like, check for arguments, check that the arguments look like email addresses, if not then maybe it is a file, check to see if it exists (throw warning/error), if so then push it to a list and go to the next one. If it is a file you could push it to a different list. Then check STDIN for input, store it to an array for your message. Then check your list of files, import them into the content list (or even better maybe you want to attach them!!). If something is missing throw an error or set some defaults, if not send the message. Take it a chunk at a time, run it hundreds of times with lots of print statements until you have what you want. The above is exactly what I needed to get me thinking! Thanks!! SNIP Consider the AppConfig module too, it has some more capability that might come in handy this time. I'll look into this, thanks. I've cobbled some code together to test stuff out with: #!/usr/bin/perl use warnings; use strict; my @addresses; my @message; if( @ARGV ) { print There are arguments\n; while( $ARGV[0] =~ /[EMAIL PROTECTED]/ ) { push @addresses, $ARGV[0].', '; shift; } print @addresses\n; } else { print There are no arguments\n; } while( ) { if( /^.$/ ) { last; } else { push @message, $_; } } print \n\nThe following message will be sent:\n; print @message\n; I keep getting a warning when the file name's not on the command line. In other words, If I use standard input for manual input, or if I pipe the input to the mailer script. # mailer [EMAIL PROTECTED] [EMAIL PROTECTED] test.txt works fine, but: # ls -l | mailer [EMAIL PROTECTED] [EMAIL PROTECTED] or # mailer [EMAIL PROTECTED] [EMAIL PROTECTED] gives the following output: # mailer [EMAIL PROTECTED] [EMAIL PROTECTED] There are arguments Use of uninitialized value in pattern match (m//) at ./mailtest4 line 15. [EMAIL PROTECTED], [EMAIL PROTECTED], This is a test message. . The following message will be sent: This is a test message. I know that the Use of unintialized value ... message has to do with the fact that input is sitting on STDIN (or, will be), but I can't figure out how to deal with it. Thanks for any help --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Extra newline characters.
On Fri, 8 Oct 2004 11:11:26 -0700 (PDT), Ron Smith [EMAIL PROTECTED] wrote: I'm working the exercises out of the Learning Perl book, but I'm doing so through a shell account from a Window$ box into a UNIX environment. I'm experiencing an oddity wherein I'm getting, what I think are, extra newlines or carriage returns in my code as I type it in the shell through a telnet session. This phenomenon, of course, throws off the results of the code. Has anyone experienced this? Is there a solution? I've tried several adjustments in the code I'm writing by using an extra 'chomp' or' chop', but this method is hit-and-miss. There may be some ENV variable or something else I can use to get some consistency going. TIA Ron What UNIX environment? What terminal emulator? I know that Solaris includes a handy utility called dos2unix that will help pull out annoying extra characters from DOS created text files. Perhaps this utility is found in other UNIXy OSs as well. --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Extra newline characters.
On Fri, 8 Oct 2004 11:51:34 -0700 (PDT), Ron Smith [EMAIL PROTECTED] wrote: I'm not sure what you mean. I'm new at logging into shell accounts through a 'telnet' session. I'm on a Window$ 2000 box, using 'telnet' to log into 'sdf.lonestar.org'. The first thing that appears at login is the following: NetBSD/alpha (sdf) (ttypu) Does that help? Ron Errin Larsen [EMAIL PROTECTED] wrote: On Fri, 8 Oct 2004 11:11:26 -0700 (PDT), Ron Smith wrote: I'm working the exercises out of the Learning Perl book, but I'm doing so through a shell account from a Window$ box into a UNIX environment. I'm experiencing an oddity wherein I'm getting, what I think are, extra newlines or carriage returns in my code as I type it in the shell through a telnet session. This phenomenon, of course, throws off the results of the code. Has anyone experienced this? Is there a solution? I've tried several adjustments in the code I'm writing by using an extra 'chomp' or' chop', but this method is hit-and-miss. There may be some ENV variable or something else I can use to get some consistency going. TIA Ron What UNIX environment? What terminal emulator? I know that Solaris includes a handy utility called dos2unix that will help pull out annoying extra characters from DOS created text files. Perhaps this utility is found in other UNIXy OSs as well. --Errin Hi again, Ron, First, try to bottom post. People on this list will snap at 'ya if your don't! Yes, that helps, it tells us what OS you're writing for, and also how you connect to that OS (DOS telnet). Now, where do you develop your scripts? Do you write your scripts on the Win2000 machine and then copy/ftp them over to the UNIX box to test/implement? The more details you give us the better able we'll be to help! --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Fwd: Extra newline characters.
-- Forwarded message -- From: Errin Larsen [EMAIL PROTECTED] Date: Fri, 8 Oct 2004 15:36:28 -0500 Subject: Re: Extra newline characters. To: Ron Smith [EMAIL PROTECTED] On Fri, 8 Oct 2004 13:24:22 -0700 (PDT), Ron Smith [EMAIL PROTECTED] wrote: SNIP Thanks for your help :-). You're welcome! I'm simply loging into a free shell account, then using 'vi', on the other end, to write the scripts. But, I get odd behavior from the shell(s) when I execute the script (again on the other end). --Ron My guess, in this case, is that you're terminal emulator (DOS) is having trouble talking to the shell. I would try some of the suggestions from Kevin: Try: $ stty sane $ TERM=vt100; export TERM That will give you a common default terminal emulation. I would recommend getting a better windows client terminal. Some good free ones are putty and teraterm. Cygwin is a complete linux emulation package the runs on windows and includes decent terminal emulators (and I believe perl comes with it). I'm wondering what shell you are using? you can type: # echo $SHELL on most UNIX accounts, this will be set for you and will contain your default shell. Kevin's suggestions will work with most shells, but Cshell would likely complain. I think your problem is more shell and terminal-emulation related, rather than Perl related. I'd suggest a good new-to-UNIX book, If I were you. Do you have a SysAdmin you can contact with problems or help-needed questions? If so, I would explain your problem to her/him as she/he (wow, that's annoying, huh? trying to keep PC is a pain!) would be most familiar with your environment and terminal options. I also agree with Kevin that a good terminal emulation program could help you. To follow Chris' advice, the really good ones will support SSH, as well. I'd suggest Putty: http://www.chiark.greenend.org.uk/~sgtatham/putty/ --Errin PS: I forgot to mention some further [EMAIL PROTECTED] mailing list etiquette: Try to CC the list with your replies, as well. Some people will complain if you don't! Keep up the UNIX and Perl learning! -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Extra newline characters.
On Fri, 8 Oct 2004 15:25:36 -0700 (PDT), Ron Smith [EMAIL PROTECTED] wrote: Thanks all. The problem was at the begining of the 'TELNET' session, I have to type in: UNSET CRLF. Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. You're welcome! and welcome to the list!! --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
CPAN help
Hi Perl Mongers, I need to configure the CPAN module to use gcc (which I've installed). Whenever I run: # perl -MCPAN -e 'install Bundle::CPAN;' the CPAN module automatically uses the cc that is in my /usr/ucb/ directory. (I'm running Solaris 9 on Sun hardware). I tried adding the following line to the CPAN Config.pm file: 'cc' = q[/usr/local/bin/gcc], But that didn't work, it still tries to use /usr/ucb/cc. What can I do? Is there a command line switch I can use? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: auto dial
On Thu, 7 Oct 2004 15:52:14 -0400 (EDT), Chris Devers [EMAIL PROTECTED] wrote: On Thu, 7 Oct 2004, Adam Saeed wrote: I want to built a opensource utility for telemarketers. Ahh, I see. Well, I'm fresh out of ideas in that case. Good luck, and let us know how it goes! :-) -- Chris Devers Wait! Why don't you give us your home telephone number and We'll call you (probably everyday) with our ideas to help you (probably when you are eating or trying to go to sleep). Won't that be nice? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Passing shell variables to PERL
On Tue, 5 Oct 2004 14:32:27 -0400, Willy Perez [EMAIL PROTECTED] wrote: Hi, Is there a method to pass a shell assigned variable to perl? For ex: ABC=xyc perl -ne 'print $ABC' In awk you could use ENVIRON[varname], is there something compatible in perl. Willy Perez Liz Claiborne IT (201) 295-7011 Hi Willy, Perl will auto-magically take all of your shell environment variables and put them in a hash: %ENV where the keys are the variable names and the values are the values! so, for your example above, # perl -e 'print $ENV{ABC}\n' should work! --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Doubt
On Mon, 4 Oct 2004 18:33:51 -0300, Sprogis, Rubens (V-Emeritis) [EMAIL PROTECTED] wrote: How can I do to concatenate 2 strings? Hi! Glad you are trying Perl! Welcome to the group! Let me offer you some advice. This mailing list works best when you write some of your own code, try it, test it and debug it yourself. THEN, if you still have trouble, post you code to this list and we'll help you. If you send us no code, we can't tell where your problem is. If you haven't written any code yet, keep in mind that we are NOT a free, code-writing service. Now, I am SURE you can find some answers to your problems on the net. I'll give you a hint. Try this web site first: http://learn.perl.org/ --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Passing options to command in a system call
On Fri, 1 Oct 2004 17:41:50 +0200, Jan Eden [EMAIL PROTECTED] wrote: Hi, Hello! SNIP How can I pass an option to system's first argument in a setting like this? (I know I can use a module instead of calling wget, but this is a more general issue.) Thanks, Jan -- This is ironic: If all else fails read the instructions. - Donald Knuth First, check out 'perldoc -f system' The answer to you question is in the first paragraph! Second, try passing EACH argument as a seperate value: ((WARNING: I don't have wget, so I couldn't test this!)) system(wget, -O, /dev/null, http://janeden.org/test/file.txt;); --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Need help with script
Hi Perlers, On 30 Sep 2004 10:11:29 +0100, Jose Alves de Castro [EMAIL PROTECTED] wrote: On Wed, 2004-09-29 at 21:25, JupiterHost.Net wrote: I would like the output in the following format object1...tabDescription1 object2...tabDescription2 object3...tabDescription3 perl -lne 'BEGIN{$/=\n\n;}s/\n/\t/;print' FILENAME perl -l -00pe's/\n/\t/' FILENAME That's pretty slick you guys, he's sure to get an A+ ;) If your teacher requires the quotes to be removed: What if the teacher requires an explanation? O:-) It is my opinion that code should be explained, at least in this list. You're trying to teach people how to fish (and maybe swim). Giving them fish is good, of course, but tell them how you got it :-) That said, nice code :-) perl -l -00pe's/\n/\t/;s/\//g;' FILENAME :) -- José Alves de Castro [EMAIL PROTECTED] http://natura.di.uminho.pt/~jac I'll give it a try. First, it's good to know that the two Perl special variables '$/' and '$\' are the input separator and output separator. By Default, they will be $/ = \n (newline character) and $\ = undef (nothing. No output separator). Now, on the command line, the '-0' option will set the input separator ($/). In the above example, it's setting $/ = 0. Also, in the example, the '-l' will do two things. First, it will automatically chomp() whatever's in '$/', and then it will set the output separator to be whatever the input separator will be. So, specific to our example, first '-l' sets '$\' (output separator) to whatever '$/' is (at this point, it's \n, or a newline). Then, the '-0' switch is setting the $/ = 0 ( or null, or nothing!). OK, next we have '-p' and '-e'. The '-e' tells Perl to read one line (the one after the '-e') and use that as the code to process. The '-p' causes Perl to assume the following code around your code: LINE: while( ) { # your code goes here } continue { print or die -p destination: $!\n; } So, this is going to process whatever files it finds on your command line and then print '$_'! Now, the code that's going into that block is, in our example: s/\n/\t/; s/\//g; So, we get this as the code Perl is running: LINE: while( ) { s/\n/\t/; # Change newlines into tabs s/\//g; # Remove all double-quotes } continue { print or die -p destination: $!\n; } but with the special $/ = 0 as the input separator and $\ = \n as the output separator! There! Am I right? This is fun ... we should do this more often! This taught me a lot. BTW, I found most of these explanations in the 'perldoc perlrun' and 'perldoc perlvar' pages. You can check out continue blocks with 'perldoc -f continue'. --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Need help with script
Hi Paul, Thx for the response On Thu, 30 Sep 2004 15:30:06 +0200, Paul Johnson [EMAIL PROTECTED] wrote: SNIP Pretty close: $ perl -MO=Deparse -l00pe's/\n/\t/;s/\//g' BEGIN { $/ = \n; $\ = \000; } LINE: while (defined($_ = ARGV)) { chomp $_; s/\n/\t/; s///g; } continue { print $_; } -e syntax OK which shows a little confusion over $/ and $\, and an unnecessary \ in the initial program. This taught me a lot. Good :-) -- Paul Johnson - [EMAIL PROTECTED] When I run your command line up there, I get the following: # perl -MO=Deparse -l00pe's/\n/\t/;s/\//g' LINE: while (defined($_ = ARGV)) { chomp $_; s/\n/\t/; s///g; } continue { print $_; } -e syntax OK What OS are you running? My '-MO=Deparse' didn't create that BEGIN Block. I'm on Solaris, using Perl 5.6.1. I'm just curious what the difference is. --Errin BTW, I didn't know about the Deparse Pre-Compiler thing! Thanks for pointing it out. It's very handy. Why do you think Perl uses: while( defined( $_ = ARGV ) ) instead of: while( ) Is this example pointing out that the diamond ( ) operator is really a short-cut for 'defined( $_ = ARGV )' ? I'll have to go read about this. What is Perl protecting against by putting that assignment in a defined()? -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: how do i describe a perl user?
On Fri, 1 Oct 2004 01:37:44 +0930, Sano Babu [EMAIL PROTECTED] wrote: just wondering what a user of Perl may be called? Perler?? Theres got to be some fancy name for it. Perl is not just another programming language.. I reckon its much more like a religion with attitude.. :) Cheers, SanoBabu I say 'Perler' when I'm addressing this list. Haven't had anyone complain yet! I haven't seen anything else! Anyone else have some suggestions? The 'Guru's on the web are at a site called Perl Monks. But what do you call a devotee, not a guru? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Need help with script
Thanks for your help guys... But the code is performing the logic only for the first set of lines... After the running the above script, the output looks like Object1...tab...Description1 Object2 Description2 Object3 Description3 Can you post EXACTLY what's in the input file for us? I test with the following input file, I called it object.txt: # cat object.txt Object1 Description1 Object2 Description2 Object3 Description3 I run this command line: # perl -l -00pe's/\n/\t/;s/\//g' object.txt Object1 Description1 Object2 Description2 Object3 Description3 It's hard to see the tabs, so I tried one with 2 tabs in it for clarity: # perl -l -00pe's/\n/\t\t/;s/\//g' object.txt Object1 Description1 Object2 Description2 Object3 Description3 So, on my (Solaris 9, Perl 5.6.1) box, it's working. What OS and Perl version are you using and what's your input file look like? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: difference between @_ and shift
I am (admitedly) unfamiliar with OO Perl. I understand enough to grok what you are saying, Wiggins, but I have a question. Does a sub (like the one above) have a problem with being called with as opposed to not being called with an with OO Perl? That questions was worded weird. Let me try again. As I understand it, if you call a sub with 'subname', the sub's @_ variable will share the calling scope's @_ variable, BUT, if you call the sub with 'subname()' it will get it's own, fresh @_. is that true? And if it is, does this affect the subs being used with OO Perl? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Configuration File
Hi Perlers, I'm trying to implement one of the recipes I found in the Perl Cookbook. It is 8.16. Reading Configuration Files recipe. Here are some snippets from that text: ... Or better yet, treat the config file as full Perl code: do $ENV{HOME}/.progrc; ... The second solution uses do to pull in raw Perl code directly. When used with an expression instead of a block, do interprets the expression as a filename. This is nearly identical to using require, but without risk of taking a fatal exception. ... You might wonder what context those files will be executed under. They will be in the same package that do itself was compiled into. Typically you'll direct users to set particular variables, which, being unqualified globals, will end up in the current package. If you'd prefer unqualified variables go into a particular package, do this: { package Settings; do $ENV{HOME}/.myprogrc } As with a file read in using require or use, those read in using do count as a separate and unrelated lexical scope. That means the configuration file can't access its caller's lexical (my) variables, nor can the caller find any such variables that might have been set in the file. It also means that the user's code isn't held accountable to a pragma like use strict or use integer that may be in effect in the caller. My code looks like this (for testing): #!/usr/bin/perl # configtest.pl use warnings; use strict; { package Config; do configtest.conf } print $_\n for( @Config::FILE_NAME ); My configtest.conf file looks like this: # A list of file names @FILE_NAME = qw[ /This/is/a/test /This/is/also/a/test /And/this/is/the/last/test ]; Now, this code runs, and produces the expected output. However, it also gives me a warning: Name Config::FILE_NAME used only once: possible typo at ./configtest.pl line 7. I realize I can just turn my pragmas off after testing/implementation to get rid of this, but is there a better way? Perhaps my Perl Cookbook is just old (yup, 1st edition. Has this recipe been updated?) --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Need help with script
On 30 Sep 2004 19:52:31 -, PerlDiscuss - Perl Newsgroups and mailing lists [EMAIL PROTECTED] wrote: I am using Cygwin on Win2K and the version of perl on it is v5.8.0 I am using the same input file, but when I run the command you ran, the output looks like Object1 Description1 Object2 Description2 Object3 Description3 Thanks Hi again, Just to let you know, most on this list will become upset with you if you don't bottom-post. For future reference ... Ok, I've got ActiveState on WinXP, 5.8.4 ... I tried and found that I had the same problems as you. After much playing around, I found it's a quoting problem on the command line (at least, in my case it was). I just don't have a good grasp of quoting rules and precedence in DOS I guess. Here's what I did to make it work on my DOS command line: C:\ perl -l -00pe s/\n/\t/;s/\//g object.txt I basically just removed the single-quotes from around the code in the '-e' option. That gave me the output I was looking for. Try it and let us know. --Errin BTW, anyone have a good reference for DOS quoting rules/precedence? -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Configuration File
On Thu, 30 Sep 2004 23:30:16 +0200, Gunnar Hjalmarsson [EMAIL PROTECTED] wrote: Nothing prevents you from declaring @FILE_NAME: package Config; our @FILE_NAME; do configtest.conf; print $_\n for @FILE_NAME; -- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl doesn't that kinda defeat the purpose of declaring the Config name space? I was trying to keep the variables in the configtest.conf file in a different name space than the main program. I don't HAVE to do this, just thought it seemed like a good way to keep the two, potentially conflicted, name spaces apart. I wanted to see the variables created in the Config name space require a dereference (is that the right word?), ala Config::FILE_NAME. That way, if the main code ALSO has a FILE_NAME variable, the contents of the (at run time, unknown to the main developer) config file. I hope that's making sense. --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Fwd: UNIX Process List (U)
On Wed, 29 Sep 2004 07:52:53 -0400, Meidling, Keith, CTR, ISD [EMAIL PROTECTED] wrote: UNCLASSIFIED Is there a module to get a list of processes on a UNIX/Linux machine, or would I just do a `ps` and save it to an array? -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response Hi Keith, Check out Proc::ProcessTable on CPAN. That might be what you're looking for. --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: current directory
Hi Urs, You should look at Cwd: perldoc Cwd That capital C in Cwd is relevant. --Errin On Wed, 29 Sep 2004 15:24:06 +0200, Urs Wagner [EMAIL PROTECTED] wrote: Hello How can I find out the current directory? I call chdir, afterwards I should switch back to the old one. Thanks Urs -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: How to access first key of Hash of Hash
On Wed, 29 Sep 2004 22:18:49 +0800, Edward Wijaya [EMAIL PROTECTED] wrote: On 29 Sep 2004 14:58:00 +0100, Jose Alves de Castro [EMAIL PROTECTED] wrote: If I understood this correctly, you want to do this: So sorry for being not clear. I will extend just a bit. Suppose I have: my %HoH = ( firstkey = { A = 'blabla', B = 'dadada', C = 'tititi',} secondkey = { D = 'blabla', E = 'dadada', F = 'tititi',} ); and I generated that HoH with this: $HoH{$fkey}{$alpha}=$text; namely: firstkey, secondkey from $fkey A, B, C, etcfrom $alpha blabla etc from $text my question is how can I print output like: firstkey secondkey given the construction variables as mention before. Thanks Regards, Edward WIJAYA SINGAPORE -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response Jose was correct. You need to read: perldoc -f keys try this: print $_\n foreach( keys %HoH ); --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
POSIX module
Hi Perlers, I've seen a lot of tutorial or example code dealing with the POSIX module that does something like this: use POSIX ':sys_wait_h'; What does the ':' mean/do in the above line? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: POSIX module
On Wed, 29 Sep 2004 11:32:58 -0400, Jim [EMAIL PROTECTED] wrote: Hi Perlers, I've seen a lot of tutorial or example code dealing with the POSIX module that does something like this: use POSIX ':sys_wait_h'; What does the ':' mean/do in the above line? Besides googling for it, try reading: perldoc perlipc perldoc perldoc -f waitpid perldoc POSIX --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.770 / Virus Database: 517 - Release Date: 9/27/2004 Thank you Bob, and Jim I have read about this. My question is more about the 'use' code then about the POSIX module. It's just a really big module that has a lot of these tags in it, it seems. Here's my problem: When I use the following in my code, it runs and works fine: use POSIX 'setsid'; use POSIX 'errno_h'; use POSIX ':sys_wait_h'; However, when I try to combine those into one line: use POSIX qw/setsid errno_h :sys_wait_h/; Then I get the following error: # ismon.pl :errno_h is not exported by the POSIX module at /usr/perl5/5.6.1/lib/sun4-solaris-64int/POSIX.pm line 19 :sys_wait_h is not exported by the POSIX module at /usr/perl5/5.6.1/lib/sun4-solaris-64int/POSIX.pm line 19 Can't continue after import errors at /usr/perl5/5.6.1/lib/sun4-solaris-64int/POSIX.pm line 19 BEGIN failed--compilation aborted at ./ismon.pl line 3. First of all, I'm not putting a ':' in front of 'errno_h' in my code, but Perl seems to assume it's there ... why? Is there a difference between the two implementations above that I'm not seeing? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: POSIX module
On Wed, 29 Sep 2004 12:27:03 -0400, Bob Showalter [EMAIL PROTECTED] wrote: Errin Larsen wrote: When I use the following in my code, it runs and works fine: use POSIX 'setsid'; use POSIX 'errno_h'; use POSIX ':sys_wait_h'; However, when I try to combine those into one line: use POSIX qw/setsid errno_h :sys_wait_h/; Then I get the following error: # ismon.pl :errno_h is not exported by the POSIX module at /usr/perl5/5.6.1/lib/sun4-solaris-64int/POSIX.pm line 19 :sys_wait_h is not exported by the POSIX module at /usr/perl5/5.6.1/lib/sun4-solaris-64int/POSIX.pm line 19 Can't continue after import errors at /usr/perl5/5.6.1/lib/sun4-solaris-64int/POSIX.pm line 19 BEGIN failed--compilation aborted at ./ismon.pl line 3. SNIP Exporter only does the special :tag processing if the *first* entry in the import list starts with one of the following characters : ! / So move :sys_wait_h to the front and it will work. Thanks Bob, that did it. I wonder why that is about Exporter? It seems rather counter-intuitive to me. --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Opening file($ARGV) with Getopt - failing
Hi Edward! On Tue, 28 Sep 2004 18:51:12 +0800, Edward Wijaya [EMAIL PROTECTED] wrote: Hi, Why my code below fail to open and print the file contents when I do: perl mycode.pl -f filename Regards, Edward WIJAYA SINGAPORE __BEGIN__ use strict; use warnings; Good Start! Those pragmas above are very helpful! use Getopt::Std; use vars qw($f); The above is good, but is now obsolete. The preferred method is to use 'our' declarations Also, the 'getopts()' function creates variables of the form 'opt_*' where '*' is replaced with your option name. So, for example, you should have declared opt_f here: our $opt_f; getopts('f:'); my $f = $ARGV[0]; open ( INFILE, '', $f) or die $0 : failed to open input file $f : $!\n; This is good, I especially like the 'die' statement in case it fails. Good Job! It is relevant to note that opening a file to read is default, so the '' was not necessary. However, it is nice to make it obvious which way you are opening the file (read only, write, or etc.). I might have written this as follows: open INFILE, $opt_f or die $0: failed to open input file $opt_f: $!; close ( INFILE ); Why are you closing the file you just opened? Maybe it's because you don't understand the diamond ('') operator. The diamond operator will read the end of you command line and open each filename it finds there for processing. It allows you to write a Perl script that acts like any other UNIX process (e.g. cat, grep, etc ... ). In your code example, it appears as if you are trying NOT to use the diamond operator and force your user to input a single filename with the '-f' option. If this is the case, you don't want to close your 'INFILE' above until after you've used it! Like this: while( INFILE ) { print; } while ( ) { print $_; Inside this block, the '$_' variable is default and will be assigned the next line from the file that 'while' is processing. Because it is default, it is not necessary. } __END__ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response Edward, I could write this script two ways. The first is the way I prefer and it doesn't use 'Getopt::Std' at all: #!/usr/bin/perl use warnings; use strict; while( ) { print; } That code above uses the diamond operator correctly. The diamond ('') operator reads the command line and processes each file name on the command line after your command! So, in a command called 'perl_cat.pl' with a command line like: # perl_cat.pl foo.txt bar.txt The diamond operator will first open foo.txt (processed in the while loop) and print each line, then, open bar.txt and print each of it's lines! However, if you are really trying to use the 'Getopt::Std' module, I'd do it like this: #!/usr/bin/perl use warnings; use strict; our $opt_f; getopts( 'f:' ); open INFILE, $opt_f or die $0: Can't open file $opt_f: $!; while( INFILE ) { print; } In the above code, unlike yours, I don't 'close' INFILE. That's because Perl will close it for me at the end of my code. I hope this helps! --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Opening file($ARGV) with Getopt - failing
Hi again, Edward! Just so you know, you should CC the list when you reply! On Tue, 28 Sep 2004 22:26:55 +0800, Edward Wijaya [EMAIL PROTECTED] wrote: Thanks Errin, It works just as you suggested. Thanks so much for your thorough explanation. Glad that I learnt much from it. Edward, I could write this script two ways. The first is the way I prefer and it doesn't use 'Getopt::Std' at all: I need to use Getopt, as I will increase the number of user given options. Regards Edward WIJAYA I'm glad I could help!! Just wanted to mention one last thing. Just because you have to use Getopt::Std doesn't mean you can't ALSO use the diamond ('') operator. Let me demonstrate: #!/usr/bin/perl use warnings; use strict; use Getopt::Std; our $opt_p; getopts( 'p:' ); if( $opt_p ) { print You used the -p flag. The value passed was $opt_p\n; } while( ) { print; } The above will print out all the lines of the file found at the END of your command line (that's the diamond operator at work), but it will also allow you to specify some other option with a '-p'. So, if you have a text file called test.txt: Test Data More Test Data Other Test Data and you call the above program with this command line: # test_options.pl test.txt the output will be as follows: Test Data More Test Data Other Test Data if You instead use THIS command line: # test_options.pl -p foobar test.txt the output will be as follows: You used the -p flag. The value passed was foobar. Test Data More Test Data Other Test Data I hope that makes sense. Don't forget that the diamond operator will see more than one filename on that command line as well: # test_options.pl -p foobar test.txt test.txt You used the -p flag. The value passed was foobar. Test Data More Test Data Other Test Data Test Data More Test Data Other Test Data HTH --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Problem iterating over diamond (whileFILE)
Hi Edward, On Tue, 28 Sep 2004 11:20:39 -0400, Bob Showalter [EMAIL PROTECTED] wrote: Edward Wijaya wrote: Thanks a lot for your reply Bob. but can you be more specific: You need to either close and reopen the file, or rewind the file using seek() before you can re-read the data. SNIP Try this: #!/usr/bin/perl use strict; use warnings; use Getopt::Std; our $opt_f; getopts('f:'); my $trial = 2; for ( my $t = 1 ; $t = $trial ; $t++ ) { print Trial $t\n; open INFILE, $opt_f or die $0: Can't open file $opt_f: $!; while (INFILE) { print; } } As a note, in the above code, you used a line: print Trial , $t, \n; But I changed it to: print Trial $t\n; The fun part of using double quotes ( ) is that Perl will interpolate (think translate) any variables inside those double quotes that it finds! Helps with reducing your typing AND has the added benifit of making your code more readable! When you use 'open' twice on the same file handle, it will first close that file handle, then RE-open it with the input ready to go at the beginning again! -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Opening file($ARGV) with Getopt - failing
On Tue, 28 Sep 2004 15:26:08 -0400 (EDT), Chris Devers [EMAIL PROTECTED] wrote: On Tue, 28 Sep 2004, Errin Larsen wrote: On Tue, 28 Sep 2004 18:51:12 +0800, Edward Wijaya [EMAIL PROTECTED] wrote: use vars qw($f); The above is good, but is now obsolete. That is debatable. Gather round, and listen to the story of a log handling utility SNIP It's worth it to be aware of the downsides of using a modern feature like `our`, and to be confident that it really does make more sense to use it over some older approach. It may be that the new ways really are better -- I'm certainly not against progressing the language -- but if a new feature breaks otherwise good code, is it worthwhile? -- Chris Devers So, what was the justification for changing 'use vars' to 'our'? Did the developers just want to shave down the keystrokes? Was it an understandability (is that a word?!) issue? Is there any (deep down, underneath it all) internal difference between the two? Is there a resource to read about this issue? (I did read the link you supplied, but it didn't go into WHY this changed.) The advice I was giving in this thread was based on the following quote in my 'perldoc Getopt::Std' documentation. (A quote from that): Note that, if your code is running under the recommended use strict 'vars' pragma, you will need to declare these package variables with our: our($opt_foo, $opt_bar); Later in the docs it DOES say that if you don't want to declare these as global variables, 'getopts()' will accept a hash reference. (Another quote): For those of you who don't like additional global variables being created, getopt() and getopts() will also accept a hash reference as an optional second argument. Hash keys will be x (where x is the switch name) with key values the value of the argument or 1 if no argument is specified. Like this: getopts('oif:', \%opts); # options as normal. Values in %opts I have a feeling that that way is the most correct way. That way the values being grabbed off the command line options will be scoped specifically where you want them to be instead of being globals. comments? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
SIGZERO
Hi Perlers, I'm trying to check on the status of a process by sending a SIGZERO to it with kill(). This SHOULD (according to the docs I've been reading) return false if the process died. But mine is not. It always returns true. if( kill 0 = $pid ) { print the process is OK\n; } else { print Something happened to the process: $!\n; } And for me, the above ALWAYS returns true. I'm wondering if this is something to do with Solaris, and not Perl. Maybe this signal doesn't behave the same way under Solaris? Ok, In the middle of writing this email I decided to write up a quick and dirty test: #!/usr/bin/perl use warnings; use strict; my $pid = shift; if( kill 0 = $pid ) { print Everything's ok\n; } else { print $pid is not ok: $!\n; } When I run this code against a made up PID (I grep for it first to be sure it's not really there), It works as expected, and: 17455 is not ok: No such process is returned! That's good! that's what I want. but when I throw it in my larger, longer Daemon script, it doesn't do it right. Just to give some more explaination, My script daemonizes itself: sub daemonize { chdir '/' or die Can't chdir to /: $!; open STDIN, '/dev/null' or die Can't read /dev/null: $!; open STDOUT, '/dev/null' or die Can't write to /dev/null: $!; defined( my $pid = fork ) or die Can't fork the monitor: $!; exit if $pid; setsid or die Can't start a new session: $!; open STDERR, 'STDOUT' or die Can't dup STDOUT: $!; } then, It starts a bunch of children, capturing all of their process ID in a hash: sub start_servers { my $cmdName = shift; defined( my $pid = fork ) or die Can't fork the server $cmdName: $!; if( $pid == 0 ) { # Child chdir '/' or die Can't chdir to /: $!; open STDIN, '/dev/null' or die Can't read /dev/null: $!; open STDOUT, '/dev/null' or die Can't write to /dev/null: $!; setsid or die Can't start a new session: $!; open STDERR, 'STDOUT' or die Can't dup STDOUT: $!; exec( $cmdName ); } else { # Parent $children{$pid} = $cmdName; } } Then, the original goes into a loop, checking the children and (for debug purposes at the moment) just prints some status: do { foreach( keys %children ) { if( kill 0 = $_ ) { print - $_: $children{$_} is still ok.\n; } else { print * $_: $children{$_} is not responding: $!\n; } } sleep 5; } while( 1 ); But ... I always get back the TRUE response, - 17455: ./dummy_script is still ok.. Did I miss something? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: SIGZERO
On Fri, 24 Sep 2004 09:17:58 -0500, Errin Larsen [EMAIL PROTECTED] wrote: Hi Perlers, I'm trying to check on the status of a process by sending a SIGZERO to it with kill(). This SHOULD (according to the docs I've been reading) return false if the process died. But mine is not. It always returns true. SNIP But ... I always get back the TRUE response, - 17455: ./dummy_script is still ok.. Did I miss something? --Errin I guess I should have pointed out that, at the OS prompt, I'm 'kill -9' ing one of those dummy_script processes so I can test what happens when it dies. --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: SIGZERO
On Fri, 24 Sep 2004 10:31:36 -0400, Ed Christian [EMAIL PROTECTED] wrote: Errin Larsen wrote: Hi Perlers, snip if( kill 0 = $pid ) { snip Forgive me if I presume too much, but shouldn't the above be: if( kill 0, $pid ) { perldoc -f kill Jenda is correct. I like to think of '=' as The FANCY comma!!. It's just a pretty way of typing a comma for just such an occasion when you want you code to reflect what you're doing. So, in the above, I'm sending a signal to $pid, so the big arrow shows that the signal (0) is being sent to that process ($pid)! Perl is Fun!!! This works great (and is seen most often) in hash declarations: my %demo_hash = ( Key_One = 1, Key_Two = 2, Key_Three = 3 ); -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: SIGZERO
Ok, I learned something else ... When I type: kill -9 SOME_PROCESS_ID on the command line, It's not actually killing the process. Let me explain. My script starts 3 others and then stays around watching them. So, when I run it, I get this: # ps -ef | grep dummy user1 18000 1 0 10:04:22 ?0:00 dummy_monitor user1 18001 18000 0 10:04:22 ? 0:00 dummy1 user1 18002 18000 0 10:04:22 ? 0:00 dummy2 user1 18003 18000 0 10:04:22 ? 0:00 dummy3 (the names have been changed to protect the innocent!) Now ... After I run a kill: # kill -9 18002 # ps -ef | grep dummy user1 18000 1 0 10:04:22 ?0:00 dummy_monitor user1 18001 18000 0 10:04:22 ? 0:00 dummy1 user1 18003 18000 0 10:04:22 ? 0:00 dummy3 However, I just discovered that if I check the PID instead: # ps -ef | grep 18002 user1 180002 18000 0 0:00 defunct See that defunct?! How did my process get a defunct status? Is that a Solaris-fancy way of saying zombie-child? The above explains why my (kill 0 = $pid) isn't working the way I expect, but How can I kill the kid. The defunct child process finally dies if I kill the parent (original dummy_monitor) script. Does this mean that my setsid line in my original script is not working correctly? I'm confused here. --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: SIGZERO
On Fri, 24 Sep 2004 17:20:44 +0200, Jenda Krynicky [EMAIL PROTECTED] wrote: From: Errin Larsen [EMAIL PROTECTED] See that defunct?! How did my process get a defunct status? Is that a Solaris-fancy way of saying zombie-child? I believe so. The above explains why my (kill 0 = $pid) isn't working the way I expect, but How can I kill the kid. The defunct child process finally dies if I kill the parent (original dummy_monitor) script. Does this mean that my setsid line in my original script is not working correctly? I'm confused here. I believe you are supposed to wait()/waitpid() on your children. Or install a $SIG{SIGCHLD} handler that reaps the children. I haven't used Perl under any Unix for years so I can't give you the details. perldoc perlipc should help. Jenda Yup. I tried putting: $SIG{CHLD}='IGNORE'; in my parent and that prevents the zombie child. So, next question! how do I wait() or waitpid() on more than one process? don't both of those make the wait()ing process sit still and do nothing else until it gets a return? I'll read perlipc again (man that's a hard one to grok) and see what it says. --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: SIGZERO
On Fri, 24 Sep 2004 10:34:50 -0500, Errin Larsen [EMAIL PROTECTED] wrote: On Fri, 24 Sep 2004 17:20:44 +0200, Jenda Krynicky [EMAIL PROTECTED] wrote: From: Errin Larsen [EMAIL PROTECTED] SNIP how do I wait() or waitpid() on more than one process? don't both of those make the wait()ing process sit still and do nothing else until it gets a return? I'll read perlipc again (man that's a hard one to grok) and see what it says. --Errin Well, I found the following code snippet in perlipc: sub REAPER { my $child; while( ( $child = waitpid( -1, WNOHANG ) ) 0 ) { $Kid_Status{$child} = $?; } $SIG{CHLD} = \REAPER; } $SIG{CHLD} = \REAPER; This seems to do something similar to what I want, but I'm confused about exactly what it's doing. what does the '-1' argument to waitpid() do? What is the 'WNOHANG' flag? Why are we reassigning '$SIG{CHLD}' to 'REAPER' inside of REAPER (this seems redundant to me!) I realize this is getting away from the beginner focus of this mailing list, but I don't currently belong to any other mailing lists. Thanks for any help you can throw at me. --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: SIGZERO
On Fri, 24 Sep 2004 11:52:19 -0400, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I am a beginner, but I love to see all the knowledge transfer so keep the moderate to difficult questions coming! SNIP I'm like you, Derek! I love just reading this stuff. Satisfies some inner-geek need I have! On Fri, 24 Sep 2004 10:34:50 -0500, Errin Larsen [EMAIL PROTECTED] wrote: On Fri, 24 Sep 2004 17:20:44 +0200, Jenda Krynicky [EMAIL PROTECTED] wrote: From: Errin Larsen [EMAIL PROTECTED] SNIP SNIP This seems to do something similar to what I want, but I'm confused about exactly what it's doing. what does the '-1' argument to waitpid() do? What is the 'WNOHANG' flag? Why are we reassigning '$SIG{CHLD}' to 'REAPER' inside of REAPER (this seems redundant to me!) SNIP Ok, I found this is the Perl Cookbook. Below is a quote: To avoid accumulating dead children, simply tell the system that you're not interested in them by setting $SIG{CHLD} to IGNORE. If you want to know which children die and when, you'll need to use waitpid. The waitpid function reaps a single process. Its first argument is the process to wait for - use -1 to mean any process - and its second argument is a set of flags. We use the WNOHANG flag to make waitpid immediately return 0 if there are no dead children. A flag value of 0 is supported everywhere, indicating a blocking wait. Call waitpid from a SIGCHLD handler, as we do in the Solution, to reap the children as soon as they die. The wait function also reaps children, but it does not have a non-blocking option. If you inadvertently call it when there are running child processes but none have exited, your program will pause until there is a dead child. Now, why can't the {perldoc -f waitpid} tell me use -1 to mean any process ?!? That would have been helpful!! --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Daemon that starts other Daemons
Hi perl-people, I'm not sure if this is beginners stuff, but I'll post here 'cause it's the only list I'm subscribed to at the moment. I'm writing a script that will daemonize itself, and then watch some processes. If one of those processes die, it will start it again. So, I've been reading the perlipc docs and I found this handy code on proper daemonization: use POSIX 'setsid'; sub daemonize { #it's polite for daemons to chdir to root so that they #don't prevent a filesystem from being unmounted chdir '/' or die Can't chdir to /: $!; #it's also polite for daemons to redirect all output to #/dev/null so users don't get random output open STDIN, '/dev/null' or die Can't read /dev/null: $!; open STDOUT, '/dev/null' or die Can't write to /dev/null:$!; #the parent get's the new child's pid back, the child gets '0' back defined( my $pid = fork ) or die Can't fork: $!; #here's where I start having problem. This code assumes that #the parent will be exiting, thus leaving the child able #to run setsid exit if $pid; setsid or die Can't start a new session: $!; open STDERR, 'STDOUT' or die Can't dup STDOUT: $!; } perlipc goes on to explain: The fork() has to come before the setsid() to ensure that you aren't a process leader (the setsid() will fail if you are). So, my question is, how do I implement this code WITHOUT the parent process dieing? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Daemon that starts other Daemons
On Thu, 23 Sep 2004 11:23:16 -0500, Errin Larsen [EMAIL PROTECTED] wrote: Hi perl-people, SNIP So, my question is, how do I implement this code WITHOUT the parent process dieing? --Errin I found that (at least on the Solaris OS that I'm working on) that the setsid function will setup a new session UNLESS: The calling process is already a process group leader, or the process group ID of a process other than the calling process matches the process ID of the calling process. So, I think that's saying that as long as the process (the child) does not have any children of it's own, then I'll be ok with the above code! Is that what the blurb above is saying? (Why are UNIX docs always so darn hard to read!!?) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Daemon that starts other Daemons
-- Forwarded message -- From: Errin Larsen [EMAIL PROTECTED] Date: Thu, 23 Sep 2004 16:30:21 -0500 Subject: Re: Daemon that starts other Daemons To: Wiggins d Anconia [EMAIL PROTECTED] Hi again, Ok ... so with some research and playi^H^H^H^H^Htesting I've found the answer to what's really been bothering me. If I fork(), I get the PID of the resulting child. However, if THAT child runs and external command, how do I get the (now grand)child's PID. The answer I was looking for was a deeper understanding of exec(). by fork()ing a child and having that child run exec(), the exec()ed command will have the SAME process ID as the original child. In actuality, the exec()ed command is NOT a grandchild, but has taken over the original child's process and all it's environment (STDIN, STDOUT, %ENV, etc.). That's what I needed to know! Now, if I just collect and keep the child's PID, when I run the exec() I'll have the PID of whatever command was exec()ed. Also, with some experimenting, the setsid() doesn't NEED the original parent to die to work, it just needs the child to be forked before it runs setsid(). In other words, if you try to run setsid() BEFORE you fork the child (in an attempt to give both the child and the parent the same session and group ID, perhaps) it will fail. If you instead have the child run setsid() after it is fork()ed, it will run fine, whether the parent is dead or not! YAY!! On Thu, 23 Sep 2004 13:30:08 -0600, Wiggins d Anconia [EMAIL PROTECTED] wrote: On Thu, 23 Sep 2004 11:23:16 -0500, Errin Larsen [EMAIL PROTECTED] wrote: Hi perl-people, SNIP So, my question is, how do I implement this code WITHOUT the parent process dieing? --Errin SNIP Thanks for the help, Wiggins. I agree this would all be easier if I just went a grabbed a module, but for (probably strange) reasons I'd rather not go into, I want to do this from scratch. Also, this has been extremely helpful in teaching me what's going on with the backticks, system(), fork() and exec() functions. This process has really helped me along with my Perl education. Also, I realized that the ORIGINAL parent needs to die (So as to disassociate the daemons from the calling terminal/process), but I was looking for a daemon that would run, start other servers, and that hang around monitoring them. I think we're talking about the same thing here, just I didn't explain it will originally. Now, I just need to implement some code to dump a file with PIDs into /var/run! Thanks for the suggestions/help and I'll get working on it now! --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Run a process in the background
Hi Perlers, I know that questions like this get asked all the time, but I guess it's just my turn to ask 'em! I need to kick of some processes in my script. However, the script needs to kick them all off at once and then stick around to do some other things. I'm kinda new to Perl, but in my OS's shell, I'd do this (actually, I DO do this ... this Perl script will be replacing this shell script): #!/bin/sh nohup /path/to/process/one/bin/server.sh /dev/null 21 nohup /path/to/process/two/bin/server.sh /dev/null 21 nohup /path/to/process/three/bin/server.sh /dev/null 21 I figure I can pass that string directly to system() in Perl, system nohup /path/to/process/one/bin/server.sh /dev/null 21 ; system nohup /path/to/process/two/bin/server.sh /dev/null 21 ; system nohup /path/to/process/three/bin/server.sh /dev/null 21 ; but that invokes the shell, right? Also, I'd like to capture the Process ID of those 3 servers. So I tried the above and it works, but I'd still like to be able to leave the shell out of this. And what about those process IDs? One last question. If I do the above, does the OS consider those 3 servers my scripts children? I know that comes with some responsibility (I've been looking at some things about the SIGCHLD signals). oh, and btw, this is Solaris I'm talking about here. Thanks guys and gals, --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: simple windows process list
On 21 Sep 2004 13:03:21 -, Peter Scott [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], [EMAIL PROTECTED] (Jp) writes: The object of the code below is to output a list of space seperated fields with PID, username and process. The code generates te correct output. My guess is that my perl code can be smaller. Who dares? Don't care about smaller. Care about clearer. Sometimes the two go together. SNIP It is better design to have a subroutine that returns the values you want than to print them so close to having figured them out. One day you may want to do something other than printing them and you would like to be able to use the same code. -- Peter Scott http://www.perldebugged.com/ *** NEW *** http://www.perlmedic.com/ Hi JP, I implemented some of Peter's suggestions for you, including making the meat of this code a subroutine for future use. Here's the sub: sub proclist { my %output; foreach my $line ( `tasklist /v /nh` ) { chomp( $line ); $line ne or next; # extract PID my $pid = substr($line, 26, 6); # remove leading spaces $pid =~ s/^\s*//; # extract username my $user = substr($line, 88, 50); # remove trailing spaces $user =~ s/\s*$//; # extract process my $proc = substr($line, 0, 24).substr($line, 152, 72); # change multiple spaces to single spaces $proc =~ s/\s+/ /g; # remove trailing N/A $proc =~ s/N\/A\s*$//g; # build the return hash $output{$pid} = join( ':', $user, $proc ); } return %output; } And here's some code that uses that sub to produce the output you were looking for: #!perl # # Object: # To output a tab separated list of PID, username and process # for windows XP # # Prerequisites: # 1) ActiveState Perl # 2) Windows XP use warnings; use strict; # here is an example of using the sub 'proclist' to produce the output # you described. Notice that # split(':', $proclisthash{$pid}) # will seperate the user info from the process info for you my %plist = proclist(); foreach my $pid( keys %plist ) { my( $out_pid, $out_user, $out_proc ) = ( $pid, split( ':', $plist{$pid} ) ); print $out_pid\t$out_user\t$out_proc\n; } cheers, --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Delete all hash entries except for a specific list
On Tue, 21 Sep 2004 14:58:43 -0400 (EDT), Jeff 'japhy' Pinyan [EMAIL PROTECTED] wrote: On Sep 21, Bob Showalter said: my %hash = ( foo = 1, bar = 2, baz = 3, qux = 4, ); I would like to remove all the entries in the hash except for 'bar' and 'qux'. (Actual hash has other entries which can vary at runtime. I know that I only want to keep 'bar' and 'qux' however). my @keys = qw(bar qux); You could do: my %keep_these_keys; @keep_these_keys{qw( bar qux )} = (); delete @hash{ grep !exists $keep_these_keys{$_}, keys %hash }; -- Jeff japhy Pinyan % How can we ever be the sold short or RPI Acacia Brother #734 % the cheated, we who for every service http://japhy.perlmonk.org/ % have long ago been overpaid? http://www.perlmonks.org/ %-- Meister Eckhart So ... is there a way to return a 'not' slice of hashes? What I mean is, the 'keys' function returns a list of all keys in a slice. Is there a function to return a list of all keys in slice EXCEPT those keys that I explicitely pass? like this, maybe: my %my_hash = ( foo = 1, bar = 2, baz = 3, qux = 4, ); my @other_keys = not_keys( %my_hash, foo, bar ) and then @other_keys = qw( baz qux ) ??? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
declaring with my
Hi all, straight out of the Learning Perl book (3rd edition, page 275) is this code: my @numbers; push @numbers, split while ; foreach (sort { $a = $b } @numbers) { printf %20g\n, $_; } This works flawlessly. My question is why can't I put that variable declaration in the push function? like this: push my @numbers, split while ; foreach (sort { $a = $b } @numbers) { printf %20g\n, $_; } When I run this code, nothing is output. It seems I see this kind of variable-declaration-in-a-function all the time. Why is it not working here? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: declaring with my
Because the push() statement is in a loop, and my() would empty the variable at each iteration. -- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl Hi Gunnar ... Thanks for the help. I assure the list, the following is the code EXACTLY as I was using it to test: #!/usr/bin/perl use warnings; use strict; my @numbers; push @numbers, split while ; foreach (sort { $a = $b } @numbers) { printf %20g\n, $_; } This works flawlessly, with no warnings or error messages. I tried to modify the script, as seen below: #!/usr/bin/perl use warnings; use strict; push my @numbers, split while ; foreach (sort { $a = $b } @numbers) { printf %20g\n, $_; } This code produces no output ... not even any warnings or errors. Gunnar, I believe your explanation makes the most sense to me. With the my operator (function?) reseting the value of the @numbers variable each time the loop is run, the output would not be in error, it would just be empty. So, now my question becomes, is there a way to watch this variable, before, throughout and after the loop to confirm that it is being reset each time. More specifically, my problem now is, if the variable is being reset throughout the loop, shouldn't the final iteration of the loop have produced SOME output, albeit only the last bits? Maybe it has something to do with the precedence of the actual line of code in the loop. the: push my @numbers, split; --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: CC mit Mailprog funktioniert nicht
Ok ... in the spirit of universal Perl-ing, I'll try to translate the below for the rest of us on the list! I put my notes that are in the code inside --( )-- marks. I'm not really good at this sort of thing, but with the help of some Google-ing and what not, here goes ... On Fri, 10 Sep 2004 01:38:20 +0200, Reinhold Riedersberger [EMAIL PROTECTED] wrote: Hallo , Hello, ich habe ein für mich seltsames Problem: I have a problem that is strange for me: Mit dem untenstehenden Programmteil habe ich früher (meine ich zumindest) erfolgreich eMails nebst CC versendet. With the following program section I have successfully dispatched emails together with CC before. Seit mir unbekannter Zeit wird aber nur noch der To-Empfänger amgemailt. Since there are an unknown quantity of 'To-Recipients time is however only amgemailt. (I don't have any idea what amgemailt means!) Das CC erscheint dann dort zwar im Kopf, aber das Mail geht nicht dorthin. The CC appears then there in the head, but the Mail does not go there. Es wird also nur ein Mail versendet. Thus only one Mail is sent. Das gleiche wenn ich testweise die To-Zeile noch einmal kopiere. (I can't figure this line. something like: ) The same thing if I (test point? test-wise?) the To-Line still only copies. Es geht nur ein Mail raus, keine zwei. Only one mail goes out, not two. (I'm assuming that raus was a typo for aus, which means 'out' ... otherwise, I don't know what raus means!) Die Variablen sind korrekt bestückt. Those variables are correctly equipped. Was mache ich falsch? What mistake am I making? (or, What am I doing wrong?) open ( MAIL , |$mailprog -t) || die Kann $mailprog nicht öffnen!\n; print MAIL To: [EMAIL PROTECTED]; # Dummy-Empfänger --(Empfanger just means recipient)-- print MAIL Cc: $zieladressen\n; --(ziel means goal, adressen = address)-- print MAIL Subject: $thema-Anfrage\n; --(Thema= Topic, Anfrage = Inquiry)-- print MAIL From: $email\n; print MAIL Reply-to: $email\n; print MAIL Sehr geehrte Damen und Herren,\n\n; --(Ladies and Gentleman)-- print MAIL bitte erstellen Sie uns ein $thema-Angebot anhand der folgenden Angaben:\n\n; --(Something like: please provide us with a topic-inquiry (quote?) )-- --(based on the following data)-- -- Mit freundlichen Grüssen Yours sincerely, Reinhold -- -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: CC mit Mailprog funktioniert nicht
On Fri, 10 Sep 2004 09:09:43 -0500, Errin Larsen [EMAIL PROTECTED] wrote: Ok ... in the spirit of universal Perl-ing, SNIP Oops ... I didn't realize he re-posted to the list in English ... Never Mind! --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: How to dynamically taking the multiple input arguments?
Well, I'm kinda new at this stuff myself, but Here's a couple of things I see right away: On Sat, 11 Sep 2004 10:27:44 +0800, Edward WIJAYA [EMAIL PROTECTED] wrote: Hi, SNIP #!/usr/bin/perl -w --You don't really need to use the -w flag here AND the 'use warnings' in your subroutine down below. use strict; -- Nice Job!! use Data::Dumper; if(scalar @ARGV ne 1) { print Usage: $0 file1 file2 [file3] etc\n; exit(1); } #the above part doesn't seem to be working well/useful --Try this: unless( @ARGV = 2 ) { die Usage: $0 file1 file2 [file3...]\n; } my $file1 = $ARGV[0]; --This is easier and prettier with this: my $file1 = shift; my @set1 = get_file_data($file1); #Remove the whitspace and \n from each lines @set1 = grep { s/^\s+//; s/\s+$//; s/\s+/ /g; length } @set1; --You can get all the \n's out at once with a chomp: chomp @set1; However, the whole get_file_data thing and chomping can all be done like this: open INFILE, $filename or die Couldn't open $filename: $!\n; chomp( my @filedata = INFILE ); Then, to clear out the whitespace from each line: foreach( @filedata ) { s/\s+//g; } my $s1 = [EMAIL PROTECTED]; my $file2 = $ARGV[1]; my @set2 = get_file_data($file2); @set2 = grep { s/^\s+//; s/\s+$//; s/\s+/ /g; length } @set2; my $s2 = [EMAIL PROTECTED]; my $file3 = $ARGV[2]; my @set3 = get_file_data($file3); @set3 = grep { s/^\s+//; s/\s+$//; s/\s+/ /g; length } @set3; my $s3 = [EMAIL PROTECTED]; #Printout the appended lines from the data print map { join(,$set1[$_],$set2[$_],$set3[$_]), \n } (0..$#set1); #Subroutine sub get_file_data { my ($filename) = @_; use strict; use warnings; # Initialize variables my @filedata = (); unless ( open( GET_FILE_DATA, $filename ) ) { print STDERR Cannot open file \$filename\\n\n; exit; } @filedata = GET_FILE_DATA; close GET_FILE_DATA; return (@filedata); } SNIP Not much, I know, but I'm sure some of the others on the list will help out more. I'll work on this some more and post what I figure out later. --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: How to dynamically taking the multiple input arguments?
Here ya go ... this works for me. I tested it with up to 5 input files and it was still workin'. It does have a bug, though. It doesn't check whether all the input files are the same length. Nor did I test what happens when they AREN'T the same length. Let me know what ya think: #!/usr/bin/perl use warnings; use strict; unless( @ARGV = 2 ) { die Usage: $0 file1 file2 [file3...]\n; } my @results; foreach( @ARGV ) { open IN, $_ or die Couldn't open $_: $!\n; chomp( my @data = IN ); close IN; foreach( @data ) { s/\s+//g; } foreach( 0..$#data ) { $results[$_] .= $data[$_]; } } foreach( @results ) { print $_\n; } --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: How to dynamically taking the multiple input arguments?
On Fri, 10 Sep 2004 12:44:51 -0400, David Greenberg [EMAIL PROTECTED] wrote: foreach( @ARGV ) { open IN, $_ or die Couldn't open $_: $!\n; chomp( my @data = IN ); close IN; foreach( @data ) { s/\s+//g; } foreach( 0..$#data ) { $results[$_] .= $data[$_]; } } This is a little shorter and saves on iterations: for my $file (@ARGV) { open IN, $file or die Couldn't open $file: $!\n; @results = map { my $line = $_; chomp $line; $line =~ s/\s+//g; $line } (IN); close IN; } -David Can you throw the 'chomp' in the assignment in that 'map' statement? Then, can you also throw in the substitution in the mix? like this: @results = map{ my $line = chomp( s/\s+//g ); } ( IN ); And if so, why not this: @results = map{ chomp( s/\s+//g ) } ( IN ); As long as we're playing Perl-Golf!! I truly don't understand what 'map' is doing. Can you explain it to me? I have tried to read perldoc -f map but it's a little weird and hard to follow! --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: How to dynamically taking the multiple input arguments?
On Fri, 10 Sep 2004 13:17:40 -0400, David Greenberg [EMAIL PROTECTED] wrote: I'm no expert, but chomp won't give you what you think it will: my @arr = ('a', b\n, c\n); print join (,,chomp (@arr)); This will print: 2 while this: my @arr = ('a', b\n, c\n); chomp (@arr); print join (,,@arr); will print: a,b,c Map will run whatever is in the code block (between the {}'s) on every value in the list passed to it (between the ()'s). The last statement in the code block is like a return value. Map builds the results list out of all of the return values. With a foreach loop, it would be: my @results = (); foreach (IN) { my $line = $_; chomp $line; $line =~ s/\s+//g; push (@results, $line); #appends $line to the @results list } Hope this helps. -David Thanks, David, for the 'map' explanation. However, I've been playing with this code, and, after your suggestion (above) it seems to be broken. Originally, the question was, taking atleast 2 seperate text files on the command line, smoosh them together like this: # ./smoosher file1 file2 OneFirst TwoSecond ThreeThird if our text files are: file1: One Two Three file2: First Second Third The code I have so far is (after your suggestion): smoosher: #!/usr/bin/perl use warnings; use strict; unless( @ARGV = 2 ) { die Usage: $0 file1 file2 [file3...]\n; } my @results = (); foreach my $file ( @ARGV ) { open IN, $file or die Couldn't open $file: $!\n; @results = map { my $line = $_; chomp $line; $line =~ s/\s+//g; $line } (IN); close IN; } foreach( @results ) { print $_\n; } The first 'foreach' block in my original code, which was working, was: foreach my $file ( @ARGV ) { open IN, $file or die Couldn't open $file: $!\n; chomp( my @data = IN ); close IN; foreach( @data ) { s/\s+//g; } foreach( 0..$#data ) { $results[$_] .= $data[$_]; } } So my question is, how can we use the map function, as you suggest, to reduce the number of iterations, yet still keep our desired output? The key was the $results[$_] .= $data[$_]; line in there, which appended the current files line to the results array, as opposed to replacing it, which is what our new code seems to do. --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: How to dynamically taking the multiple input arguments?
On Sat, 11 Sep 2004 02:20:32 +0800, Bee [EMAIL PROTECTED] wrote: foreach( @ARGV ) { open IN, $_ or die Couldn't open $_: $!\n; chomp( my @data = IN ); close IN; foreach( @data ) { s/\s+//g; } foreach( 0..$#data ) { $results[$_] .= $data[$_]; } } This is a little shorter and saves on iterations: for my $file (@ARGV) { open IN, $file or die Couldn't open $file: $!\n; @results = map { my $line = $_; chomp $line; $line =~ s/\s+//g; @results seems would be re-assigned when the next file comes... Besides, I guess chomp is not nesessary here.. \s+ means [\t\r\n\f]+, so \r, \n or \r\n would seem to be cleared by the s expression. $line } (IN); close IN; } I would suggest to write in this way : my @res = (); foreach( @ARGV ) { open IN, $_ or die Couldn't open $_: $!\n; my @data = IN; close IN; s/\s+//g for @data; @res = ( @res, @data ); } Code not been tested, but the concept is something like this. HTH Ok ... Thanks for helpin' out, HTH! I tried out your suggestions and now the code looks like this: #!/usr/bin/perl use warnings; use strict; unless( @ARGV = 2 ) { die Usage: $0 file1 file2 [file3...]\n; } my @results = (); foreach my $file ( @ARGV ) { open IN, $file or die Couldn't open $file: $!\n; my @data = IN; close IN; s/\s+//g foreach( @data ); @results = ( @results, @data ); } foreach( @results ) { print $_\n; } But now the output is as follows. We want the output to look like this: OneFirst TwoSecond ThreeThird But instead, it's coming out like this: One Two Three First Second Third Given the two test input files: file1: file2: OneFirst TwoSecond Three Third --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: How to dynamically taking the multiple input arguments?
On Fri, 10 Sep 2004 15:01:34 -0400, David Greenberg [EMAIL PROTECTED] wrote: Opps, I missed that. Instead of: @results = map { my $line = $_; chomp $line; $line =~ s/\s+//g; $line } (@data); try: my @newresults = map { my $line = $_; chomp $line; $line =~ s/\s+//g; shift (@results) . $line } (@data); @results = @newresults; -David Ok ... please forgive my n00b-ness, but can you help me understand a couple of things here. This part: shift (@results) . $line Is it the same as: shift @results . $line I'm thinking no. But I don't know what the difference is. I also don't understand what exactly that shift is doing, but if I understand the difference with the parens maybe It'll start to make more sense to me. --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Fwd: How to dynamically taking the multiple input arguments?
I forgot to CC the list with my last post! sorry, won't happen again. --Errin -- Forwarded message -- From: Errin Larsen [EMAIL PROTECTED] Date: Fri, 10 Sep 2004 15:46:33 -0500 Subject: Re: How to dynamically taking the multiple input arguments? To: Bee [EMAIL PROTECTED] Alrighty ... So the code I've got now is below. Some of the variables' names have changed to make things slightly less confusing (probably only less confusing for me!). I also moved those parens arount the 'shift' function so it communicates the precendence (again, in my opinion) a little more clearly. I have tested this and it seems to work! comments? #!/usr/bin/perl use warnings; use strict; unless( @ARGV = 2 ) { die Usage: $0 file1 file2 [file3...]\n; } my @final_results = (); foreach my $file ( @ARGV ) { open IN, $file or die Couldn't open $file: $!\n; my @tmp_results = map{ s/\s+//g; ( shift @final_results ).$_ } ( IN ); @final_results = @tmp_results; close IN; } print $_\n foreach( @final_results ); btw, thanks for all the help and explanations David and Bee (sorry about my ignorance of the HTH!). I hope Edward (the original poster!) has been paying attention! --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Leading zero in a string
Hi All, I have a variable I'm reading off of the command line: my $option = shift; That variable should hold a number between 1 and 31 (yes, a day of the month) I am checking to make sure that the number does indeed lie in that range. However, I need to pass that variable to another system command which expects any day value less than 10 to have a leading zero, so 7th day of the month should say '07'. How can I check for that leading zero? If it's missing, I know I could easily: $option = 0.$option; But I can't seem to figure out an easy, clean way to check for it. --Thanks, --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Leading zero in a string
Excellent! Thank you. I knew it was something easy, just hadn't kick-started my brain yet this morning. But I've got another one. What if the user input, say, '007' on the command line? How can I strip that off? I think I can check for it with something like this: /^0?[1-9]/ But If I find it, how do I strip it off? --Errin On Thu, 9 Sep 2004 19:39:34 +0530, Sid [EMAIL PROTECTED] wrote: Use the following: $option = 0 . $option if ($option / 10 1 $option !~ /^0/); ~Sid On Thu, 9 Sep 2004 08:58:36 -0500, Errin Larsen [EMAIL PROTECTED] wrote: Hi All, I have a variable I'm reading off of the command line: my $option = shift; That variable should hold a number between 1 and 31 (yes, a day of the month) I am checking to make sure that the number does indeed lie in that range. However, I need to pass that variable to another system command which expects any day value less than 10 to have a leading zero, so 7th day of the month should say '07'. How can I check for that leading zero? If it's missing, I know I could easily: $option = 0.$option; But I can't seem to figure out an easy, clean way to check for it. --Thanks, --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response -- http://www.upster.blogspot.com -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
regex on the command line
Hi Perl-Buddies, I'm wondering how to get a regex into my code at run-time. I mean in a command line like this: # my_perl_program foo(\w|and|or)+bar foobar.txt and in my code I want to be able to search the foobar.txt file with the regex found in the quotes. So if I assign the above to a variable: my $regex = shift; How do I use the regex in $regex in a m// oeration? Do I just throw it in there? /$regex/ That seems to work, but is it doing what I think it's doing? I may be over-thinking myself here, but it just seems too easy! --Errin Larsen -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Comparing Arrays' Values
Hi guys (and gals!), I want to compare a constant, known (expected values) array with the results I'm collecting in another array. Something like this, but I don't think this works the way I want it to: my @rray1 = qw( One Two Three ); chomp( my @rray2 = STDIN ); print The 2 arrays are the same\n if( @rray1 eq @rray2 ); So that if I enter: Oneenter Twoenter Threeenter ctrl-D on the terminal when I run the code, It will print The 2 arrays are the same on the next line. However, my tests seem to indicate I don't really know what's happeneing when I: @rray1 eq @rray2 Can someone help me? --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Collecting Data in an Output File
Hi Perl Gurus! I am collecting temperature data from the CPUs in my system. I want to write this data into a comma-seperated text file, like so: CPU1,65,63,62,64 CPU2,65,64,64,62 CPU3,64,65,66,64 Each line represents one CPU's temperature readings. Each column represents the time the reading was taken. So, if I was taking the readings once an hour, the above sample would be, for example, 12 Noon, 1pm, 2pm and 3pm. I have successfully coded some Perl that pulls that data from the system, but now I need to be able to a) determine if the file is empty and, if so, start the file by adding the CPUx output. b) if the file is not empty, add the next set of readings to the end of each line. for a), I know I can do: if( -e FILE) that's no problem. My problem is b). How can I read in all the lines into their on arrays and add some data to the end? my @wholefile = FILE; Puts all the lines, one line per array element (with \n at the end). So, I can easily iterate through and chomp the \n out, then I can add the latest temperature reading onto the end. Ok, maybe I answered my own question. So, let me take it a step further. What if I wanted to read a particular time's data out of the file; or add one into the middle? Can I get an array of arrays, Where one Array holds other arrays, each other array holding the data (split into elements) of one line? --Thanks -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Collecting Data in an Output File
On Tue, 31 Aug 2004 14:07:14 -0400 (EDT), Chris Devers [EMAIL PROTECTED] wrote: On Tue, 31 Aug 2004, Errin Larsen wrote: I am collecting temperature data from the CPUs in my system. SNIP This is nitpicking, but have you considered inverting that? A format like this might be easier to work with: time,cpu1,cpu2,cpu3 Tue Aug 31 12:00:00 EDT 2004,65,65,64 Tue Aug 31 13:00:00 EDT 2004,63,64,65 Tue Aug 31 14:00:00 EDT 2004,62,64,66 Tue Aug 31 15:00:00 EDT 2004,64,62,64 This way, you can simply append to the file with the timestamp and the readings from each of the CPUs you're monitoring, rather than having to open the file and append to each line. The downside is that if you add CPUs, the file falls apart because you need to add / change / remove a column. The fix for this is to just have one CPU per line, and identify it: time,cpu,temp Tue Aug 31 12:00:00 EDT 2004,cpu1,65 Tue Aug 31 12:00:00 EDT 2004,cpu2,65 Tue Aug 31 12:00:00 EDT 2004,cpu3,64 ... This is more verbose, obviously, but also more flexible. The above is good stuff. I'll work on this. There are some problems, but I'll get to them below. How can I read in all the lines into their on arrays and add some data to the end? For the one I've got above, it would be something like... while ( ) { my ($ts, $cpu, $temp) = split(, $_); push (@{ $processors{$cpu} }, $temp); } Then to get at the data, do something like foreach $cpu ( sort keys %processors ) { print $cpu: @{ $processors{ $cpu }}\n } ...or something like that... SNIP Thanks Chris. This is the sort of thing I was looking for! Now I'll go play with your suggestions some. The problem I'm gonna have is that the file format I suggested is really what I need. HOWEVER, I don't need that format when I'm collecting the data, just when I get ready to use that data. So I think I'll try collecting it as you suggest in the 2nd suggestion above, and then work on a script that will convert THAT file into the format I need. Thanks again! --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: is possible start some actions with Perl without Cron?
Ok, since no one wanted to help me with this, I needed to look through some googled stuff to find the answer myself. In the spirit of helping beginers (which of course I am) I'll post what I found! (This material is from page 2 of the tutorial there): quote There are several rules or characteristics that most daemons possess. If a daemon does not follow these basic rules, it will most likely become a demon and wreak havoc on your system. Fork and Exit The first thing a daemon should do is fork() a child process and have the parent process exit(). This is necessary for several reasons. First, it disassociates the process from the controlling terminal, or the login shell. Second, it removes the process from the process group that initiated the program. This ensures that the process is not a process group leader, which is required for setsid() to run successfully. Call setsid() setsid() is a POSIX function that turns the process into a session leader, group leader, and ensures that it doesn't have a controlling terminal. Change Working directory The current working directory should be changed with chdir to the root directory (/). This is necessary to avoid using a working directory that resides on a mounted partition. If the process is started on a mounted partition, the system administrator wouldn't be able to unmount the partition until the process was halted. You could, of course, specify a different working directory as long as it doesn't reside on a remotely mounted partition. File Creation Mode The umask determines the default permissions new files are assigned. Setting umask to 0 removes the defaults that might otherwise disable permissions the daemon intended to enable when creating files. Close Unneeded File Handles Besides closing any filehandles that might have been opened, daemons often redirect STDIN to read from, and STDOUT and STDERR to write to /dev/null. open STDIN, '/dev/null' or die Can't read /dev/null: $!; open STDOUT, '/dev/null'; open STDERR, '/dev/null'; Logging Messages In some cases, you may want to record an error or messages to a log file on the system. This can be accomplished by redirecting STDOUT and STDERR to one or more log files. open STDOUT, $access_log or die Can't write to $access_log: $!; open STDERR, $error_log or die Can't write to $error_log: $!; /quote This material was all found at the following link: http://www.webreference.com/perl/tutorial/9/ and is authored by ... well, here's a cut-n-paste of the about page: About Mother of Perl - Mother of Perl is a free biweekly how-to devoted to all things Perl. Perl has been an integral part of the Web developer's toolkit for years now. There are probably more Perl scripts, tools, and libraries available for Web Development than any other modern language. This column will attempt to address the needs and concerns of the Desparate Perl Hacker© by providing practical, powerful, and elegant solutions to everyday problems in 100 lines of code or less. If you would like to see a topic or problem area covered in Mother of Perl, please let me know by sending me some feedback. The Author - Jonathan Eisenzopf is an author, teacher, and consultant who has worked with companies like Netscape, Chrysler, Mecklermedia, Bell Atlantic, and Litton/PRC to deploy large scale Web-based information systems. He is presently a Principal Software Engineer and VP of Technology at Whirlwind Interactive, based in the Washington D.C. area. Jonathan is active in the Perl and XML communities by delivering presentations to user groups, contributing articles to publications such as The Perl Journal, authoring modules for CPAN, and maintains www.perlxml.com, an information clearinghouse for Perl and XML resources. Jonathan is also a co-author of an upcoming book from O'Reilly and Associates covering Perl and XML. On Tue, 24 Aug 2004 15:59:57 -0500, Errin Larsen [EMAIL PROTECTED] wrote: Hi, Can you help me understand the below a little better. As I understand what's going on, the Process (let's say PID=100) spawns a child with the fork() function (let's say PID=200). This (200) is assigned to $pid in the parent, and zero (0) is assigned to $pid in the child. So, what does my $pid=fork() resolve to in each case? I'll assume that it resolves to the PID that fork returns. So, in the parent, the statement resolves to 200 and the unless statement doesn't resolve. In the child, the statement resolves to 0 and the unless statement DOES resolve. So, the parent prints a message to STDOUT and quits, while the child keeps on running (in the little do/while loop) doing that stuff that's in there :) Ok ... so, um, why go through all this? Why not just write your do/while block and just execute it in the background on the command line? is fork() doing something else that helps a daemon that I'm not aware of? --Errin On Sat, 21 Aug 2004 09:53:23 -0400, Adam Rosi-Kessel [EMAIL PROTECTED] wrote: SNIP
Re: is possible start some actions with Perl without Cron?
Hi, Can you help me understand the below a little better. As I understand what's going on, the Process (let's say PID=100) spawns a child with the fork() function (let's say PID=200). This (200) is assigned to $pid in the parent, and zero (0) is assigned to $pid in the child. So, what does my $pid=fork() resolve to in each case? I'll assume that it resolves to the PID that fork returns. So, in the parent, the statement resolves to 200 and the unless statement doesn't resolve. In the child, the statement resolves to 0 and the unless statement DOES resolve. So, the parent prints a message to STDOUT and quits, while the child keeps on running (in the little do/while loop) doing that stuff that's in there :) Ok ... so, um, why go through all this? Why not just write your do/while block and just execute it in the background on the command line? is fork() doing something else that helps a daemon that I'm not aware of? --Errin On Sat, 21 Aug 2004 09:53:23 -0400, Adam Rosi-Kessel [EMAIL PROTECTED] wrote: SNIP Here's the skeleton of it: unless (my $pid = fork()) { do { SendEmailToUsers; sleep 3 * 24 * 60 * 60; } while (1); } print Starting email daemon...\n; - That's all. This will run indefinitely, and every three days run the subroutine SendEmailToUsers. You obviously need to add a lot more to SNIP -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: pulling out a,an, the from beginning of strings
Hey, Ok, looking through this ... I'm confused. SNIP Perhaps: $scalar =~ s/^(a|an|the)\s*\b//i; would work better. SNIP Is this capturing into $1 the a|an|the (yes) and the rest of the title into $2 (no?). After doing so, will it reverse the two ( i.e. s/^(a|an|the)\s+(.*)\b/$2, $1/i )? Also, what is the \b? it seems that the trailing i is for ignoring case; is that correct? Just need some help with RE!! thanks, --Errin -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Translate sed / Perl
Hey guys (and gals, I imagine!), I'm really new to perl. I've been working through some beginners tutorials and now I need (want!) to use perl to overhaul something I wrote in the past. I've got a script (in bash) that I use that has a particular sed command in it. The command is as follows: sed -n '/System Temperatures/,/==*/p' FILENAME The file in question has text that looks like this: BEGIN FILE SAMPLE No failures found in System === = Environmental Status = System Temperatures (Celsius): --- Device Temperature Status --- CPU0 65 OK CPU1 63 OK CPU2 64 OK CPU3 63 OK MB 35 OK IOB 30 OK DBP0 32 OK = Front Status Panel: --- Keyswitch position: NORMAL END FILE SAMPLE (obviously, this is output from the Sun Solaris' prtdiag -v command!) I want to collect just the temperature data from this file, so I use the above sed command to pull out only the lines: BEGIN SAMPLE System Temperatures (Celsius): --- Device Temperature Status --- CPU0 65 OK CPU1 63 OK CPU2 64 OK CPU3 63 OK MB 35 OK IOB 30 OK DBP0 32 OK = END SAMPLE What I'm looking for is a graceful way to do this in a perl script. I'm kinda at a loss for where to begin. Can you help me out? Thanks, --Errin Larsen -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Translate sed / Perl
Thx ... That is exactly what I was looking for! I was really only missing the '..' part. Thanks again! --Errin On Fri, 13 Aug 2004 06:46:08 -0700, John W. Krahn [EMAIL PROTECTED] wrote: Errin Larsen wrote: Hey guys (and gals, I imagine!), Hello, I'm really new to perl. I've been working through some beginners tutorials and now I need (want!) to use perl to overhaul something I wrote in the past. I've got a script (in bash) that I use that has a particular sed command in it. The command is as follows: sed -n '/System Temperatures/,/==*/p' FILENAME The same thing written in Perl would be: perl -ne 'print if /System Temperatures/../=+/' FILENAME The file in question has text that looks like this: [snip file sample] What I'm looking for is a graceful way to do this in a perl script. I'm kinda at a loss for where to begin. Can you help me out? A simple example would be something like this: #!/usr/bin/perl use warnings; use strict; my $file_in = 'FILENAME'; open my $IN, '', $file_in or die Cannot open $file_in: $!; while ( $IN ) { if ( /System Temperatures/ .. /=+/ ) { print; } } __END__ John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: awk like question
um, can anyone explain the 'print' function below to me? specifically ... this: 'print @F[0,5]' How do I use this idea in a script instead of a command line? also, how is the input getting into this function? I mean, I understand $_ and all, but on a command line, are we piping to that command? what's with the '@F'? Thanks for the help! --Errin On Fri, 13 Aug 2004 09:52:04 -0400, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Thanks too all who passed some knowledge on, but I ended up using : while (D) { ## look for 9840S and ebexpire ## declare OFS = tab ## tell split to split on IRS 0,15. very similar to awk print $ if (($_ =~ /9840S/) ($_ =~ /ebexpire, ebexpire/ )) { local $, = \t; print FOO +(split)[0,1,5], $/; #print +(split)[0,1,5], $/; Derek B. Smith OhioHealth IT UNIX / TSM / EDM Teams 614-566-4145 John W. Krahn [EMAIL PROTECTED] 08/13/2004 08:51 AM To: Perl Beginners [EMAIL PROTECTED] cc: Subject:Re: awk like question [EMAIL PROTECTED] wrote: All, Hello, wasn't sure if this was received b/c I got a reurne to sender error. How can I print certain fields delimited by ' '? In awk I would write awk '{print $1, $6}' filename The Perl equivalent of that is: perl -lane 'print @F[0,5]' Here is an out file that I want to grab data from : 04/29/04 11:00:28 [ 6687:ebexpire, [EMAIL PROTECTED] E00796 9840S 537 2B0234233543E6A4 04/29/04 11:00:28 [ 6687:ebexpire, [EMAIL PROTECTED] E00830 9840S 571 D402325A8345ABDE 04/29/04 11:00:28 [ 6687:ebexpire, [EMAIL PROTECTED] E00066 9840S 127 5202333193B75CBB 04/29/04 11:00:28 [ 6687:ebexpire, [EMAIL PROTECTED] E00501 9840S 168 4B0233BABA5813F6 I want fields one two and six or the date, time and E string. Does it matter whether I use a foreach or a while (filehandle) ? You could write that in Perl as: perl -lane 'print @F[0,1,5]' John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: awk like question
ok. I'm not getting my question across clearly. Let me try again. I have a collection of data in a text file. Here is an example: ## foobar.txt ## one two three A B C yes nomaybe In a script (not on the command line) I want to be able to parse this data so that the first two elements in each line of the file end up in a hash as a key/value pair. If I was to declare this hash I'm refering to in a perl script in a literal context, I imagine it would look like this, given the above text file: my %myhash = ( one=two, A=B, yes=no ); Perhaps I'm wrong (I am rather new to this Perl stuff!). However, I do not want to declare it literally, I want to parse the file to create that hash. The code to parse the file, extract the first two elements of each line of that file and create a hash of key/value pairs using those first two elements is what I would like to know how to do! Thx! --Errin On 13 Aug 2004 16:57:00 +0100, Jose Alves de Castro [EMAIL PROTECTED] wrote: On Fri, 2004-08-13 at 16:51, Errin Larsen wrote: um, can anyone explain the 'print' function below to me? specifically ... this: 'print @F[0,5]' The -a signal splits the input lines and stores the resulting elements in @F Example: perl -nae 'print $F[1]\n' file.txt where file.txt contains one two three four five six prints: two five Also, although this splitting on spaces, you can also use the -F signal to define what you're splitting in. See `perldoc perlrun` HTH, jac PS: Oh, print @F[0,5], of course, prints the first six elements of @F, and since they're between double quotes, they're joined with whatever is in $ (usually a space) How do I use this idea in a script instead of a command line? also, how is the input getting into this function? I mean, I understand $_ and all, but on a command line, are we piping to that command? what's with the '@F'? Thanks for the help! --Errin On Fri, 13 Aug 2004 09:52:04 -0400, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Thanks too all who passed some knowledge on, but I ended up using : while (D) { ## look for 9840S and ebexpire ## declare OFS = tab ## tell split to split on IRS 0,15. very similar to awk print $ if (($_ =~ /9840S/) ($_ =~ /ebexpire, ebexpire/ )) { local $, = \t; print FOO +(split)[0,1,5], $/; #print +(split)[0,1,5], $/; Derek B. Smith OhioHealth IT UNIX / TSM / EDM Teams 614-566-4145 John W. Krahn [EMAIL PROTECTED] 08/13/2004 08:51 AM To: Perl Beginners [EMAIL PROTECTED] cc: Subject:Re: awk like question [EMAIL PROTECTED] wrote: All, Hello, wasn't sure if this was received b/c I got a reurne to sender error. How can I print certain fields delimited by ' '? In awk I would write awk '{print $1, $6}' filename The Perl equivalent of that is: perl -lane 'print @F[0,5]' Here is an out file that I want to grab data from : 04/29/04 11:00:28 [ 6687:ebexpire, [EMAIL PROTECTED] E00796 9840S 537 2B0234233543E6A4 04/29/04 11:00:28 [ 6687:ebexpire, [EMAIL PROTECTED] E00830 9840S 571 D402325A8345ABDE 04/29/04 11:00:28 [ 6687:ebexpire, [EMAIL PROTECTED] E00066 9840S 127 5202333193B75CBB 04/29/04 11:00:28 [ 6687:ebexpire, [EMAIL PROTECTED] E00501 9840S 168 4B0233BABA5813F6 I want fields one two and six or the date, time and E string. Does it matter whether I use a foreach or a while (filehandle) ? You could write that in Perl as: perl -lane 'print @F[0,1,5]' John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response -- José Alves de Castro [EMAIL PROTECTED] http://natura.di.uminho.pt/~jac -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response