Re: nested subroutines
Chris Stinemetz wrote: Thanks in advance. I have a subroutine inside another subroutine in a module I am tyring to put together. I would like to pass the value assigned to $srt in the while loop as the parameter for the session_attempts subroutine called withing the processPegs subroutine. The error I am getting is: Use of uninitialized value $_srt in numeric ne (!=) at ... The code provided does not use the ne operator nor does it use the variable $_srt John -- Any intelligent fool can make things bigger and more complex... It takes a touch of genius - and a lot of courage to move in the opposite direction. -- Albert Einstein -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: nested subroutines
Sent from my iPhone On Mar 2, 2013, at 7:49 PM, John W. Krahn jwkr...@shaw.ca wrote: Chris Stinemetz wrote: Thanks in advance. I have a subroutine inside another subroutine in a module I am tyring to put together. I would like to pass the value assigned to $srt in the while loop as the parameter for the session_attempts subroutine called withing the processPegs subroutine. The error I am getting is: Use of uninitialized value $_srt in numeric ne (!=) at ... The code provided does not use the ne operator nor does it use the variable $_srt John -- Any intelligent fool can make things bigger and more complex... It takes a touch of genius - and a lot of courage to move in the opposite direction. -- Albert Einstein -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/ Correct. I was able to figure it out. Thanks, Chris -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: nested loops
MMH == Mark M Huntress mar...@bgsu.edu writes: MMH I want to nest a for loop in a for loop in a while loop, and I MMH can't even get just the first nesting to work yet. Here is the MMH relevant part of my scripting. MMH open(XYZ,$ARGV[0]ready.xyz); don't use @ARGV stuff like that before you check that you have args. always check for success with open calls also use lexical handles for i/o. all of these are common points you can google for more info MMH #while (XYZ) { MMH #chomp($_); MMH for ($z = 0, $z = $#sortedstart, $z++) { where did you get that syntax from? it isn't any normal perl loop. in fact it is a foreach loop over 3 values (afaict) and nothing close to what you envisioned it to be. read perldoc perlsyn for the two ways to write for loops - a c style and a perl foreach style. yours is a strange conjunction of the two styles and makes no sense at all. uri -- Uri Guttman -- u...@stemsystems.com http://www.sysarch.com -- - Perl Code Review , Architecture, Development, Training, Support -- - Gourmet Hot Cocoa Mix http://bestfriendscocoa.com - -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: nested loops
On 10-12-20 07:04 PM, Mark M Huntress wrote: open(XYZ,$ARGV[0]ready.xyz); The three argument open is preferred and always check your opens for errors. my $file = $ARGV[0]ready.xyz; open my $xyz_fh, '', $file or die could not open $file: $!\n; #while (XYZ) { #chomp($_); while( $xyz_fh ){ chomp; for ($z = 0, $z= $#sortedstart, $z++) { for ($i = $sortedstart[$z], $i= $sortedend[$z], $i++) { It's hard to determine what these for statements are doing without knowing what's in the arrays. if ($_ =~ /^\s+$i\s+(\D).*\s+(.+\.\d+\s+.+\.\d+\s+.+\.\d+)\s+/) { For complex patterns, use the /x to allow whitespace in them. See `perldoc perlre` and read the section on Modifiers $count++; print CON $count $count $10 $2\n; } print \nz is $z\n; print \ni is $i\n; } } I am expecting it to cycle through several $i values and also $z values. When it prints the values, it only gives $z=1. Does anyone see why this isn't working? -- Just my 0.0002 million dollars worth, Shawn Confusion is the first step of understanding. Programming is as much about organization and communication as it is about coding. The secret to great software: Fail early often. Eliminate software piracy: use only FLOSS. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: nested loops
On 21/12/2010 00:04, Mark M Huntress wrote: I want to nest a for loop in a for loop in a while loop, and I can't even get just the first nesting to work yet. Here is the relevant part of my scripting. open(XYZ,$ARGV[0]ready.xyz); #while (XYZ) { #chomp($_); for ($z = 0, $z= $#sortedstart, $z++) { for ($i = $sortedstart[$z], $i= $sortedend[$z], $i++) { if ($_ =~ /^\s+$i\s+(\D).*\s+(.+\.\d+\s+.+\.\d+\s+.+\.\d+)\s+/) { $count++; print CON $count $count $10 $2\n; } print \nz is $z\n; print \ni is $i\n; } } I am expecting it to cycle through several $i values and also $z values. When it prints the values, it only gives $z=1. Does anyone see why this isn't working? Hi Mark You have written the for statements for ($z = 0, $z= $#sortedstart, $z++) { for ($i = $sortedstart[$z], $i= $sortedend[$z], $i++) { with commas instead of semicolons. Also, this is the C form of the for loop, and almost never the right thing to do in Perl. Instead use for my $z (0 ... $#sortedstart) { for my $i ($sortedstart[$z] ... $sortedend[$z]) { The advice you have been given in the other replies is good, and you should take note of that as well. HTH, Rob -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: nested loops
Mark M Huntress wrote: I want to nest a for loop in a for loop in a while loop, and I can't even get just the first nesting to work yet. Here is the relevant part of my scripting. open(XYZ,$ARGV[0]ready.xyz); Better as: open XYZ, '', $ARGV[0]ready.xyz or die Cannot open '$ARGV[0]ready.xyz' because: $!; #while (XYZ) { #chomp($_); for ($z = 0, $z= $#sortedstart, $z++) { You are iterating over a list of three numbers. If @sortedstart is empty then you get: for $_ ( 0, 0, 0 ) { If @sortedstart is NOT empty then you get: for $_ ( 0, 1, 0 ) { What you probably want is: for my $z ( 0 .. $#sortedstart ) { for ($i = $sortedstart[$z], $i= $sortedend[$z], $i++) { Again, you are iterating over a list of three numbers. If $sortedend[$z] is less than $i you get: for $_ ( $sortedstart[$z], 0, $sortedstart[$z] ) { If $sortedend[$z] is NOT less than $i you get: for $_ ( $sortedstart[$z], 1, $sortedstart[$z] ) { What you probably want is: for my $i ( $sortedstart[ $z ] .. $sortedend[ $z ] ) { John -- Any intelligent fool can make things bigger and more complex... It takes a touch of genius - and a lot of courage to move in the opposite direction. -- Albert Einstein -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Nested if and elsif and else
Uri Guttman u...@stemsystems.com writes: i disagree that it is elegant. too often if/else lists are not needed. many can be replaced by dispatch tables. if one of the clauses does just a return or next/last that can be replaced with a modifier or shorter statement. without ANY serious work, i have over 10k lines of perl code in one system with about 10 else's and maybe 3 elsif's. it just is a matter of knowing how to manage flow control well and you rarely need else's. Can someone show an example of an if/elsif/else nested construct being replaced by a dispatch table? -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Nested if and elsif and else
Harry Putnam wrote: Uri Guttman u...@stemsystems.com writes: i disagree that it is elegant. too often if/else lists are not needed. many can be replaced by dispatch tables. if one of the clauses does just a return or next/last that can be replaced with a modifier or shorter statement. without ANY serious work, i have over 10k lines of perl code in one system with about 10 else's and maybe 3 elsif's. it just is a matter of knowing how to manage flow control well and you rarely need else's. Can someone show an example of an if/elsif/else nested construct being replaced by a dispatch table? -- Here's an example I gave in a similar question in another forum. my %dispatch = ( 1 = \getcpuinfo, 2 = \osversion, 3 = \loadaverages, 4 = \systemload_uptime, 5 = \netinterfaceinfo, 6 = \diskusage, 7 = \ipaddress, q = sub { print Goodbye\n and exit; }, error = sub { print invalid selection\n }, ); while(1) { print press 1 to get CPU Info \n, press 2 to get OS version \n, press 3 to get CPU Load averages\n, press 4 to get System Load Uptime\n, press 5 to get Net Interface info\n, press 6 to get system disk usage info \n, press 7 to get IP address info \n; press q to Exit\n chomp(my $selection) = STDIN; my $code = $dispatch{$selection} || $dispatch{'error'} ; $code-(); } -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Nested if and elsif and else
r...@i.frys.com writes: Here's an example I gave in a similar question in another forum. Thanks... I'm sorry to ask more but if someone asked to be shown an if/elsif/else construct being replaced by a dispatch table, I don't really see how that answered there question. It didn't for me. Where is the comparable if/elsif/else construct that is being replaced by the dispatch table? Visualizing how it would go is a little beyond my grasp I guess. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Nested if and elsif and else
On 4/15/10 Thu Apr 15, 2010 9:21 AM, Harry Putnam rea...@newsguy.com scribbled: r...@i.frys.com writes: Here's an example I gave in a similar question in another forum. Thanks... I'm sorry to ask more but if someone asked to be shown an if/elsif/else construct being replaced by a dispatch table, I don't really see how that answered there question. It didn't for me. Where is the comparable if/elsif/else construct that is being replaced by the dispatch table? Visualizing how it would go is a little beyond my grasp I guess. Something like this: print press 1 to get CPU Info \n, press 2 to get OS version \n, press 3 to get CPU Load averages\n, press 4 to get System Load Uptime\n, press 5 to get Net Interface info\n, press 6 to get system disk usage info \n, press 7 to get IP address info \n; press q to Exit\n chomp(my $selection) = STDIN; if( $selection eq '1' ) { getcpuinfo(); }elsif( $selection eq '2' ) { osversion(); }elsif{ $selection eq '3' ) { loadaverages(); }elseif( $selection eq '4' ) { systemload_uptime(); ]elsif( ... }else{ print Dispatch error\n; ); -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Nested if and elsif and else
On Apr 15, 9:21 am, rea...@newsguy.com (Harry Putnam) wrote: r...@i.frys.com writes: Here's an example I gave in a similar question in another forum. Thanks... I'm sorry to ask more but if someone asked to be shown an if/elsif/else construct being replaced by a dispatch table, I don't really see how that answered there question. It didn't for me. Where is the comparable if/elsif/else construct that is being replaced by the dispatch table? Visualizing how it would go is a little beyond my grasp I guess. Sorry for not posting the if/elsif/else block, but to me that part appeared to be obvious, but I guess it wasn't. I see that Jim has posted the if/elsif/else part, so I won't duplicate it. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Nested if and elsif and else
Ron Bergin r...@i.frys.com writes: Sorry for not posting the if/elsif/else block, but to me that part appeared to be obvious, but I guess it wasn't. Probably would have been for all but the densist I guess. Not the first time I've been guilty of that. I see that Jim has posted the if/elsif/else part, so I won't duplicate it. Yes, and thanks to both of you for making it clear even to me. You fella's have lots of patience. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Nested if and elsif and else
On Wednesday 14 Apr 2010 02:35:50 Mimi Cafe wrote: I think this will work, but is it elegant.? If (condition){ if (nexted_condition){ do this. } Elsif (nexted_condition){ Do that... } else{ Do something else. } } else{ Do something else.. } As other people noted, it will work - you can nest if/elsif/else's (and other flow-control constructs) arbitrarily. However, as Martin Fowler notes in his book Refactoring ( http://www.refactoring.com/ ) long functions or methods are a code smell which indicates that one should extract one-or-more functions out of them. So if you have an inner conditional, consider extracting it into a function. Often after you have such a function, you can use return COND() ? TRUE_VAL() : FALSE_VAL() ; which can avoid further clutter. Or you can consider using a dispatch table like Uri suggested. I admit I often write quick-and-dirty code that has some levels of nested constructs (primarily in mostly standalone scripts or programs) but it's better to refactor them into smaller subroutines for more serious stuff. Regards, Shlomi Fish -- - Shlomi Fish http://www.shlomifish.org/ Why I Love Perl - http://shlom.in/joy-of-perl Deletionists delete Wikipedia articles that they consider lame. Chuck Norris deletes deletionists whom he considers lame. Please reply to list if it's a mailing list post - http://shlom.in/reply . -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
RE: Nested if and elsif and else
Yes, the nested if and elsif and else makes the code difficult to read and I often get stuck trying to make sense of it all. For now, I will look to see if I can move some bit and pieces to subroutines to improve readability. Thanks guys Mimi -Original Message- From: Jim Gibson [mailto:jimsgib...@gmail.com] Sent: 14 April 2010 01:36 To: beginners@perl.org Subject: Re: Nested if and elsif and else On 4/13/10 Tue Apr 13, 2010 4:35 PM, Mimi Cafe mimic...@googlemail.com scribbled: I think this will work, but is it elegant.? Yes, it will work, and yes, it is elegant, as long as it encapsulates the logic that is required by your program. Be sure and watch your indenting, so you can mentally group the correct branches together (you are a little off in your first 'else'). Also be sure and put some comments for each conditional that explains what is happening if it is not obvious (but don't just repeat what is in the condition). Make sure the 'do this', 'do that', and 'do something else' are not too long. If they are more than a few statements, use subroutines (with good names). If (condition){ if (nexted_condition){ do this. } Elsif (nexted_condition){ Do that... } else{ Do something else. } } else{ Do something else.. } -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/ -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Nested if and elsif and else
On 2010.04.13 23:17, Kenneth Wolcott wrote: Hi; On Tue, Apr 13, 2010 at 19:54, Uri Guttman u...@stemsystems.com wrote: JG == Jim Gibson jimsgib...@gmail.com writes: JG On 4/13/10 Tue Apr 13, 2010 4:35 PM, Mimi Cafe mimic...@googlemail.com JG scribbled: I think this will work, but is it elegant.? JG Yes, it will work, and yes, it is elegant, as long as it encapsulates the JG logic that is required by your program. i disagree that it is elegant. too often if/else lists are not needed. many can be replaced by dispatch tables. if one of the clauses does just a return or next/last that can be replaced with a modifier or shorter statement. without ANY serious work, i have over 10k lines of perl code in one system with about 10 else's and maybe 3 elsif's. it just is a matter of knowing how to manage flow control well and you rarely need else's. uri I really like the switch statement (native in Perl v5.10) over anything more complicated than one if/else clause. I agree with Uri. Even switch statements can be cumbersome depending on how many cases you have. I believe that (in the majority of cases) dispatch tables are far more effective, easy to read (like a table of contents) and maintainable (ie. very easy to add to without having to worry about placement). #!/usr/bin/perl use warnings; use strict; my $dt = { simple = sub { print Simple, anon sub inline\n }, easy= sub { my $num = 1; print $num*2 .\n;}, complex = \complex, # coderef to external sub, }; sub complex { my $num = shift; # ... do a bunch of stuff print $num\n; } # call them $dt-{ simple }(); $dt-{ easy }(); $dt-{ complex }( 5 ); Steve -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Nested if and elsif and else
Hi Mimi, Mimi Cafe wrote: I think this will work, but is it elegant.? If (condition){ if (nexted_condition){ As others have noted, it will work. But as for elegance, this is a very subjective opinion and contrary to what recent comments have said, my take on it is that it depends on who intends to look at this code and what their background is. Is it just you? Or publicly available open source for potentially everyone? Or just the members of your software engineering team? Are they people with good Perl backgrounds or are their backgrounds varied and maybe might prefer if...else and switch, constructs that are available in other languages. I personally prefer switch and if..else (in that order) since they are based on keywords which my syntax highlighter picks up easily and are even shown when I print the code out. Also, I can grep for, if I need to. Regardless of what you choose, you should also use comments before the block of code to explain what it is you're doing... Ray -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Nested if and elsif and else
On 4/13/10 Tue Apr 13, 2010 4:35 PM, Mimi Cafe mimic...@googlemail.com scribbled: I think this will work, but is it elegant.? Yes, it will work, and yes, it is elegant, as long as it encapsulates the logic that is required by your program. Be sure and watch your indenting, so you can mentally group the correct branches together (you are a little off in your first 'else'). Also be sure and put some comments for each conditional that explains what is happening if it is not obvious (but don't just repeat what is in the condition). Make sure the 'do this', 'do that', and 'do something else' are not too long. If they are more than a few statements, use subroutines (with good names). If (condition){ if (nexted_condition){ do this. } Elsif (nexted_condition){ Do that... } else{ Do something else. } } else{ Do something else.. } -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Nested if and elsif and else
JG == Jim Gibson jimsgib...@gmail.com writes: JG On 4/13/10 Tue Apr 13, 2010 4:35 PM, Mimi Cafe mimic...@googlemail.com JG scribbled: I think this will work, but is it elegant.? JG Yes, it will work, and yes, it is elegant, as long as it encapsulates the JG logic that is required by your program. i disagree that it is elegant. too often if/else lists are not needed. many can be replaced by dispatch tables. if one of the clauses does just a return or next/last that can be replaced with a modifier or shorter statement. without ANY serious work, i have over 10k lines of perl code in one system with about 10 else's and maybe 3 elsif's. it just is a matter of knowing how to manage flow control well and you rarely need else's. uri -- Uri Guttman -- u...@stemsystems.com http://www.sysarch.com -- - Perl Code Review , Architecture, Development, Training, Support -- - Gourmet Hot Cocoa Mix http://bestfriendscocoa.com - -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Nested if and elsif and else
Hi; On Tue, Apr 13, 2010 at 19:54, Uri Guttman u...@stemsystems.com wrote: JG == Jim Gibson jimsgib...@gmail.com writes: JG On 4/13/10 Tue Apr 13, 2010 4:35 PM, Mimi Cafe mimic...@googlemail.com JG scribbled: I think this will work, but is it elegant.? JG Yes, it will work, and yes, it is elegant, as long as it encapsulates the JG logic that is required by your program. i disagree that it is elegant. too often if/else lists are not needed. many can be replaced by dispatch tables. if one of the clauses does just a return or next/last that can be replaced with a modifier or shorter statement. without ANY serious work, i have over 10k lines of perl code in one system with about 10 else's and maybe 3 elsif's. it just is a matter of knowing how to manage flow control well and you rarely need else's. uri I really like the switch statement (native in Perl v5.10) over anything more complicated than one if/else clause. Ken Wolcott -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: nested loop
Adams Paul wrote: Hello everyone, I have a program which navigates to a page and then extracts the links and navigates to each of those links.It works fine for the first web page(the program navigates to the first page and then extracts the links and visits all the links).When I then try to get the program to navigate to the second page (from @page)it puts a http:/// in the address bar and does not return a web page. Below is the code: use LWP::UserAgent; use HTML::LinkExtor; use URI::URL;use WIN32::IEAutomation;my $ie = Win32::IEAutomation-new( visible = 1, maximize = 1);@page=('http://www.ebay.com','http://www.google.com','http://www.nasa.gov'); $b=0;while($b100) { print $b;print@page[$b]; $url = @page[$b]; print This is $url;print @page[$url]; # for instance $ua = LWP::UserAgent-new; # Set up a callback that collect image links my @imgs = (); sub callback { my($tag, %attr) = @_; return if $tag ne 'a'; # we only look closer at img ... push(@imgs, values %attr); } # Make the parser. Unfortunately, we don't know the base yet # (it might be diffent from $url) $p = HTML::LinkExtor-new(\callback); # Request document and parse it as it arrives $res = $ua-request(HTTP::Request-new(GET = $url), sub {$p-parse($_[0])}); # Expand all image URLs to absolute ones my $base = $res-base; @imgs = map { $_ = url($_, $base)-abs; } @imgs; # Print them out print join(\n, @imgs), \n; print (@imgs[1]); for($a=0;$a10;$a=$a+1){$ie-gotoURL(@imgs[$a]);print($img);}$b++;} Any help would be appreciated Ah, John and Brian will like this one. It has very few lines :) Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
Chas Owens schreef: But Synopsis 4* says There is no foreach statement any more. It's always spelled for in Perl 6, so it always takes a list as an argument Well Perl6 isn't Perl, it's a successor to Perl. Like Perl did, Perl6 took a lot of good parts out of other languages (like Perl, Haskell, Java, etc.) to become the rather perfect language it now is. Perl6 has far more syntactical synonymity than any language I know. For example a Perl6Tidy could present your (or someone else's) Perl6 code in many different verbosities, far beyond all the different ways that s~^\s+~~, s~\s+$~~ for $text; could be rewritten into. $ perl -MO=Deparse -e's#^\s+##, s#\s+$## for $s' ; foreach $_ ($s) { s/^\s+//, s/\s+$//; } -e syntax OK -- Affijn, Ruud Gewoon is een tijger. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
On 4/21/07, Dr.Ruud [EMAIL PROTECTED] wrote: Chas Owens schreef: But Synopsis 4* says There is no foreach statement any more. It's always spelled for in Perl 6, so it always takes a list as an argument Well Perl6 isn't Perl, it's a successor to Perl. Like Perl did, Perl6 took a lot of good parts out of other languages (like Perl, Haskell, Java, etc.) to become the rather perfect language it now is. snip By that reasoning Perl 5 isn't Perl either. Every new major version of Perl has had some pretty radical stuff in it. That said, it is a design goal to let the users still write Perl 5 syntax in a compatibility mode, but if you do that then you miss out on all of the cool stuff like hyperoperators, the new rule based regexes, pointy blocks, etc. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
Chas Owens schreef: Dr.Ruud: Chas Owens: But Synopsis 4* says There is no foreach statement any more. It's always spelled for in Perl 6, so it always takes a list as an argument Well Perl6 isn't Perl, it's a successor to Perl. Like Perl did, Perl6 took a lot of good parts out of other languages (like Perl, Haskell, Java, etc.) to become the rather perfect language it now is. snip By that reasoning Perl 5 isn't Perl either. Every new major version of Perl has had some pretty radical stuff in it. s/Perl 6/Onion/ http://www.nntp.perl.org/group/perl.perl5.porters/2007/02/msg120600.html Perl 5 can be succeeded by Perl 7 or Kurila: http://www.nntp.perl.org/group/perl.perl5.porters/2007/02/msg121360.html I prefer to go from Perl 5.9.x to Perl5 v10.0. http://groups.google.co.uk/groups/search?q=future.perl.development Perl5 is here to stay. -- Affijn, Ruud Gewoon is een tijger. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
--- Chas Owens [EMAIL PROTECTED] wrote: On 4/19/07, John W. Krahn [EMAIL PROTECTED] wrote: Chas Owens wrote: Yes, foreach was aliased to for for backwards compatibility, Huh? Do you have something to back up that claim? Well, perlsyn* says The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity. (Or because the Bourne shell is more familiar to you than csh, so writing for comes more naturally.) But Synopsis 4* says There is no foreach statement any more. It's always spelled for in Perl 6, so it always takes a list as an argument So, you can either start training yourself to say for instead of foreach now or wait for culture shock down the road. It really does not matter to me which one I use b/c they both work well and seem to produce the same results in all my tested code. Its like asking me would you like that coffee with cream/sugar or black. ANSWER: I like coffee black and with cream/sugar, it does not matter much and it all depends upon my mood. Interesting though I ran perl -MO=Deparse on this code... [EMAIL PROTECTED] /cygdrive/c/temp $ cat foo1 for my $i (0 .. 3) { $i *= 3; print $i,\n; } print \n\n; for my $i (map { $_ * 3 } 0 .. 3) { print $i\n; } $ perl -MO=Deparse foo1 foreach my $i (0 .. 3) { $i *= 3; print $i, \n; } print \n\n; foreach my $i (map {$_ * 3;} 0..3) { print $i\n; } foo1 syntax OK So is foreach really dead or going away? BTW Great write up Chas! $ perl -v This is perl, v5.8.7 built for cygwin-thread-multi-64int (with 1 registered patch, see perl -V for more detail) __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
There's been mentions of efficiency. I'm under the impression that for the uses Perl is put to, the efficiency of a loop is sorta irrelevent. If you are doing harddrive/network access, the performance gain of one loop over the other is more of less invisible. Come to think of it, the time for interpretting got to overshadow the performance gain... For running mathematical stuff, wouldn't you use C? -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
Chas Owens wrote: On 4/19/07, John W. Krahn [EMAIL PROTECTED] wrote: Chas Owens wrote: Yes, foreach was aliased to for for backwards compatibility, Huh? Do you have something to back up that claim? Well, perlsyn* says The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity. (Or because the Bourne shell is more familiar to you than csh, so writing for comes more naturally.) But Synopsis 4* says There is no foreach statement any more. It's always spelled for in Perl 6, so it always takes a list as an argument So, you can either start training yourself to say for instead of foreach now or wait for culture shock down the road. I see nothing about backwards compatibility in there? ;-) but, like telnet and rsh, it should not be used in new code. Really? I assume you mean the protocols and not the programs? The protocols and the programs (unless you are using the telnet program for manual testing of server protocols). Yes, the telnet program is a lot more useful than just using the telnet protocol. [ snip ] Which still proves the point, for(;;) is no better than while (1) for infinite loops. In my opinion while is better since I will eventually realize that this should not be an infinite loop. my $continue = 1; $SIG{__TERM__} = sub { $continue = 0 }; while ($continue} { } my $continue = 1; $SIG{ __TERM__ } = sub { $continue = 0 }; for ( ;$continue; } { } John -- Perl isn't a toolbox, but a small machine shop where you can special-order certain sorts of tools at low cost and in short order. -- Larry Wall -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
yitzle wrote: There's been mentions of efficiency. I'm under the impression that for the uses Perl is put to, the efficiency of a loop is sorta irrelevent. If you are doing harddrive/network access, the performance gain of one loop over the other is more of less invisible. Come to think of it, the time for interpretting got to overshadow the performance gain... For running mathematical stuff, wouldn't you use C? Probably FORTRAN. :-) John -- Perl isn't a toolbox, but a small machine shop where you can special-order certain sorts of tools at low cost and in short order. -- Larry Wall -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
On 4/20/07, yitzle [EMAIL PROTECTED] wrote: There's been mentions of efficiency. I'm under the impression that for the uses Perl is put to, the efficiency of a loop is sorta irrelevent. If you are doing harddrive/network access, the performance gain of one loop over the other is more of less invisible. Come to think of it, the time for interpretting got to overshadow the performance gain... I was trying to address all arguments for the use of C-style for. In general, though, premature optimization is a waste of time. You should be aware of the general cost of the constructs you use (that is why I occasionally post benchmarks for alternate algorithms), but you should be more concerned with making what you write clearly express your intent. This is why I prefer my @a = (0 .. 10); my $i = 0; for my $elem (grep {not $i++ % 3} @a) { func($elem); } to for (my $i = 0; $i @a; $i += 3) { func($a[$i] } The grep clearly states that I am looking for something and its block tells me what the criteria are. For running mathematical stuff, wouldn't you use C? Nah, Fortran. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
On 4/20/07, John W. Krahn [EMAIL PROTECTED] wrote: snip I see nothing about backwards compatibility in there? ;-) snip Nope, I could not find any proof. I did find a merlyn quote on perlmonks that states for and foreach have always been aliased, but that is not how I remember it. But who am I to argue with Randal? snip my $continue = 1; $SIG{__TERM__} = sub { $continue = 0 }; while ($continue} { } my $continue = 1; $SIG{ __TERM__ } = sub { $continue = 0 }; for ( ;$continue; } { } snip Yes, it can be done, but which looks better? -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
Chas Owens wrote: On 4/20/07, yitzle [EMAIL PROTECTED] wrote: There's been mentions of efficiency. I'm under the impression that for the uses Perl is put to, the efficiency of a loop is sorta irrelevent. If you are doing harddrive/network access, the performance gain of one loop over the other is more of less invisible. Come to think of it, the time for interpretting got to overshadow the performance gain... I was trying to address all arguments for the use of C-style for. In general, though, premature optimization is a waste of time. You should be aware of the general cost of the constructs you use (that is why I occasionally post benchmarks for alternate algorithms), but you should be more concerned with making what you write clearly express your intent. This is why I prefer my @a = (0 .. 10); my $i = 0; for my $elem (grep {not $i++ % 3} @a) { func($elem); } to for (my $i = 0; $i @a; $i += 3) { func($a[$i] } The grep clearly states that I am looking for something and its block tells me what the criteria are. You are omitting one critical argument. For people who are stuck with older versions of Perl and in your grep() example above the foreach expression creates its list in memory which may cause the program to die if the list is large enough while the C style for loop does not have this problem. John -- Perl isn't a toolbox, but a small machine shop where you can special-order certain sorts of tools at low cost and in short order. -- Larry Wall -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
On 4/20/07, John W. Krahn [EMAIL PROTECTED] wrote: snip You are omitting one critical argument. For people who are stuck with older versions of Perl and in your grep() example above the foreach expression creates its list in memory which may cause the program to die if the list is large enough while the C style for loop does not have this problem. snip I refuse to let the fact that some people cannot/will not upgrade their copy of Perl affect how I code or advise others to code. There are still people who wrtie/maintain Perl4 scripts, should I not tell people to use the strict pragma? Even IBM is shipping a modern Perl with AIX now. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
--- Chas Owens [EMAIL PROTECTED] wrote: On 4/20/07, John W. Krahn [EMAIL PROTECTED] wrote: snip You are omitting one critical argument. For people who are stuck with older versions of Perl and in your grep() example above the foreach expression creates its list in memory which may cause the program to die if the list is large enough while the C style for loop does not have this problem. snip I refuse to let the fact that some people cannot/will not upgrade their copy of Perl affect how I code or advise others to code. There are still people who wrtie/maintain Perl4 scripts, should I not tell people to use the strict pragma? Even IBM is shipping a modern Perl with AIX now. I agree with Chas and can support the AIX notion as I work on AIX 5.3 machines which is the latest AIX. But I did not see any response about: Interesting though I ran perl -MO=Deparse on this code... So will foreach really be going away? $ cat foo1 for my $i (0 .. 3) { $i *= 3; print $i,\n; } print \n\n; for my $i (map { $_ * 3 } 0 .. 3) { print $i\n; } $ perl -MO=Deparse foo1 foreach my $i (0 .. 3) { $i *= 3; print $i, \n; } print \n\n; foreach my $i (map {$_ * 3;} 0..3) { print $i\n; } foo1 syntax OK __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
On Fri, Apr 20, 2007 at 01:47:18PM -0400, Chas Owens wrote: but you should be more concerned with making what you write clearly express your intent. This is why I prefer my @a = (0 .. 10); my $i = 0; for my $elem (grep {not $i++ % 3} @a) { func($elem); } to for (my $i = 0; $i @a; $i += 3) { func($a[$i] } The grep clearly states that I am looking for something and its block tells me what the criteria are. There are times where this list needs webcams. I'd love to have been able to have seen you as you wrote that since I find it hard to believe that anyone could have done so whilst keeping a straight face ;-) I presume that in your second example you should really be comparing against for (my $i = 0; $i 10; $i += 3) { func($i); } which just seems so much clearer to me. Fortunately, TIMTOWTDI, but with any luck I won't be maintaining your code ;-) Anyway, there seems to be a little confusion about whether for or foreach were going to be removed from the language. The main point I wanted to make was that foreach is not going away. Neither is for. At least, not in Perl5, which will still be around for a long time. They are still synonyms, and any code written now and using either of these constructs will continue to work under all Perl5 releases. -- Paul Johnson - [EMAIL PROTECTED] http://www.pjcj.net -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
On 4/20/07, oryann9 [EMAIL PROTECTED] wrote: snip So will foreach really be going away? snip If Synopsis 4* is to be believed, in Perl 6 there will not be a loop named foreach. There will be a loop named for that does the has all of the functionality of foreach (just like in Perl 5). Also the for loop will not have the C-style functionality. A new loop named loop will have that functionality. So the Perl 5 code foreach my $elem (@array) {} for (my $i = 0; $i 10; $i += 3) {} will in Perl 6 become for @array - $elem {} loop ($i = 0; $i 10; $i += 3) {} Note that the loop construct could also be written like this for 0 .. 10 : by 3 - $i {} I am not aware of any targeted release date for Perl 6 (other than when it is done), so you still have plenty of time with foreach to say your goodbyes, but I would note that many things from Perl 6 are coming early in perl 5.10: say, given/when, // (like ||, but tests for undef, not false), err (like or, but tests for undef not false), and ~~ (replaces and extends =~). * http://dev.perl.org/perl6/doc/design/syn/S04.html -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
On 4/20/07, Paul Johnson [EMAIL PROTECTED] wrote: snip The grep clearly states that I am looking for something and its block tells me what the criteria are. There are times where this list needs webctams. I'd love to have been able to have seen you as you wrote that since I find it hard to believe that anyone could have done so whilst keeping a straight face ;-) No, I really do think it is better code that expresses the intent; however, I don't like the goal behind code in the first place. How often do you take each third element of list? If you are doing that then you are most likely doing something else wrong farther up in your code. I presume that in your second example you should really be comparing against for (my $i = 0; $i 10; $i += 3) { func($i); } which just seems so much clearer to me. if your goal is to produce 0, 3, 6, and 9 then yes, it is somewhat clearer, but the very fact the you have a 10 there instead of a 9 points to the off-by-one errors that tend to plague the C-style for loop. Unfortunately we will have to wait until Perl 6 for the better solution: for 0 .. 9 : by 3 - $i {} Fortunately, TIMTOWTDI, but with any luck I won't be maintaining your code ;-) I probably wouldn't write that code. I would fix whatever was causing me to have to take every third element of a list. Anyway, there seems to be a little confusion about whether for or foreach were going to be removed from the language. The main point I wanted to make was that foreach is not going away. Neither is for. At least, not in Perl5, which will still be around for a long time. They are still synonyms, and any code written now and using either of these constructs will continue to work under all Perl5 releases. The trend going forward is to do away with foreach in favor of for, so the question becomes is there any good reason to type four more letters? -- Paul Johnson - [EMAIL PROTECTED] http://www.pjcj.net -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
Chas Owens schreef: foreach is dead, long live for. I am in favor of burying foreach as well, bu I see that many people still like to use for for the C-style construct, and foreach for the other one. -- Affijn, Ruud Gewoon is een tijger. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
From: Chas Owens [EMAIL PROTECTED] On 4/18/07, yitzle [EMAIL PROTECTED] wrote: I got an array of hashes so I am using a foreach (@arr) loop to access the hashes. How do I go about looping through the hash's keys/values? I was thinking of another foreach, but then the $_ gets a bit screwed up... Do I need to do this ? foreach(@arr) { %hash = %{$_}; foreach (keys %hash) { print $_ = $hash{$_}\n; } } foreach is dead, long live for. William is dead, long live Bill? foreach and for are two names for the same thing and just as you can call someone both William and Bill you can use foreach and for interchangeably. foreach(my $i = 0; $i $whatever; $i++) for(my $i = 0; $i $whatever; $i++) for my $x (@array) foreach my $x (@array) for (@array) foreach (@array) No difference to the computer. Use whichever reads best! I would myself use for for the C-style loops and if I use the loop as a way to create an alias for ($data-{$key}[1]{whatever}{booo}) { s/.../.../g; s/.../.../g; if (/.../) { $_ = $3-$2-$1 } } or for my $text ($data-{$key}[1]{whatever}{booo}) { $text =~ s/.../.../g; $text = foolify($text, $sumfin); } and foreach is I need to loop through a collection (array, list, keys or values of a hash, ...). Though I don't think I'm 100% consistent in this. Jenda = [EMAIL PROTECTED] === http://Jenda.Krynicky.cz = When it comes to wine, women and song, wizards are allowed to get drunk and croon as much as they like. -- Terry Pratchett in Sourcery -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
On 4/19/07, Jenda Krynicky [EMAIL PROTECTED] wrote: From: Chas Owens [EMAIL PROTECTED] snip foreach is dead, long live for. William is dead, long live Bill? foreach and for are two names for the same thing and just as you can call someone both William and Bill you can use foreach and for interchangeably. foreach(my $i = 0; $i $whatever; $i++) for(my $i = 0; $i $whatever; $i++) for my $x (@array) foreach my $x (@array) for (@array) foreach (@array) No difference to the computer. Use whichever reads best! Yes, foreach was aliased to for for backwards compatibility, but, like telnet and rsh, it should not be used in new code. I would myself use for for the C-style loops And this is why. As long as people think well, I have foreach which is for iterating and for which is for C-style loops they will continue to write C-style loops. C-style loops are bad. They are there for backwards compatibility. I can't think of a single for loop that isn't better written as a range based for loop or while loop. For instance standard range based loop for (my $i = 0; $i 10; $i++) {} for my $i (0 .. 9) {} often $i winds up being used as an index which just makes me cringe. The infinite loop for (;;) {} while (1) {} The reason C programmers give for using for (;;) is that it generates less overhead on their platform, but, at least with my tests*, while(1) is more efficient in Perl. Weirder stuff that you only tend to see people coming from a C background do for (my $node = $head; $node = $node; $node-next) {} my $node = $head; while ($node = $node-next) {} But in Perl it is rarely necessary to do this sort of loop since most functions return a list that can be iterated over using for: for my $node ($head-nodes) {} and if I use the for loop as a way to create an alias And that is a perfectly idiomatic usage; at least until given is added to the language (in 5.10 from what I hear). * benchmark Rate bare for while bare 6754/s-- -17% -31% for 8179/s 21%-- -17% while 9823/s 45% 20%-- #!/usr/bin/perl use strict; use warnings; use Benchmark; my %subs = ( for = sub { my $i; for (;;) { last if $i++ 1_000 } }, while = sub { my $i; while (1) { last if $i++ 1_000 } }, bare = sub { my $i; { last if $i++ 1_000; redo } }, ); Benchmark::cmpthese(-10, \%subs); -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
foreach is dead? dangit... I loved that. and, java 5 just put in a for loop construct that is very similar to the foreach. jen On Thursday, April 19, 2007, at 08:08AM, Chas Owens [EMAIL PROTECTED] wrote: On 4/19/07, Jenda Krynicky [EMAIL PROTECTED] wrote: From: Chas Owens [EMAIL PROTECTED] snip foreach is dead, long live for. William is dead, long live Bill? foreach and for are two names for the same thing and just as you can call someone both William and Bill you can use foreach and for interchangeably. foreach(my $i = 0; $i $whatever; $i++) for(my $i = 0; $i $whatever; $i++) for my $x (@array) foreach my $x (@array) for (@array) foreach (@array) No difference to the computer. Use whichever reads best! Yes, foreach was aliased to for for backwards compatibility, but, like telnet and rsh, it should not be used in new code. I would myself use for for the C-style loops And this is why. As long as people think well, I have foreach which is for iterating and for which is for C-style loops they will continue to write C-style loops. C-style loops are bad. They are there for backwards compatibility. I can't think of a single for loop that isn't better written as a range based for loop or while loop. For instance standard range based loop for (my $i = 0; $i 10; $i++) {} for my $i (0 .. 9) {} often $i winds up being used as an index which just makes me cringe. The infinite loop for (;;) {} while (1) {} The reason C programmers give for using for (;;) is that it generates less overhead on their platform, but, at least with my tests*, while(1) is more efficient in Perl. Weirder stuff that you only tend to see people coming from a C background do for (my $node = $head; $node = $node; $node-next) {} my $node = $head; while ($node = $node-next) {} But in Perl it is rarely necessary to do this sort of loop since most functions return a list that can be iterated over using for: for my $node ($head-nodes) {} and if I use the for loop as a way to create an alias And that is a perfectly idiomatic usage; at least until given is added to the language (in 5.10 from what I hear). * benchmark Rate bare for while bare 6754/s-- -17% -31% for 8179/s 21%-- -17% while 9823/s 45% 20%-- #!/usr/bin/perl use strict; use warnings; use Benchmark; my %subs = ( for = sub { my $i; for (;;) { last if $i++ 1_000 } }, while = sub { my $i; while (1) { last if $i++ 1_000 } }, bare = sub { my $i; { last if $i++ 1_000; redo } }, ); Benchmark::cmpthese(-10, \%subs); -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
Chas Owens wrote: On 4/19/07, Jenda Krynicky [EMAIL PROTECTED] wrote: From: Chas Owens [EMAIL PROTECTED] snip foreach is dead, long live for. William is dead, long live Bill? foreach and for are two names for the same thing and just as you can call someone both William and Bill you can use foreach and for interchangeably. foreach(my $i = 0; $i $whatever; $i++) for(my $i = 0; $i $whatever; $i++) for my $x (@array) foreach my $x (@array) for (@array) foreach (@array) No difference to the computer. Use whichever reads best! Yes, foreach was aliased to for for backwards compatibility, Huh? Do you have something to back up that claim? but, like telnet and rsh, it should not be used in new code. Really? I assume you mean the protocols and not the programs? I would myself use for for the C-style loops And this is why. As long as people think well, I have foreach which is for iterating and for which is for C-style loops they will continue to write C-style loops. C-style loops are bad. They are there for backwards compatibility. I can't think of a single for loop that isn't better written as a range based for loop or while loop. For instance standard range based loop for (my $i = 0; $i 10; $i++) {} for my $i (0 .. 9) {} How about: for ( my $i = 0; $i 10; $i += 3 ) {} foreach my $i ( ? .. ? ) {} often $i winds up being used as an index which just makes me cringe. The infinite loop for (;;) {} while (1) {} The reason C programmers give for using for (;;) is that it generates less overhead on their platform, but, at least with my tests*, while(1) is more efficient in Perl. I ran your benchmark on my computer and for(;;) and while(1) ran at about the same speed. $ perl -le' use Benchmark; my %subs = ( for = sub { my $i; for (;;) { last if $i++ 1_000 } }, while = sub { my $i; while (1) { last if $i++ 1_000 } }, bare = sub { my $i; { last if $i++ 1_000; redo } }, ); Benchmark::cmpthese(-10, \%subs); ' Rate bare for while bare 4471/s-- -15% -15% for 5253/s 17%-- -0% while 5268/s 18%0%-- $ perl -le' use Benchmark; my %subs = ( for = q{ my $i; for (;;) { last if $i++ 1_000 } }, while = q{ my $i; while (1) { last if $i++ 1_000 } }, bare = q{ my $i; { last if $i++ 1_000; redo } }, ); Benchmark::cmpthese(-10, \%subs); ' Rate bare while for bare 4445/s-- -15% -15% while 5219/s 17%-- -0% for 5233/s 18%0%-- John -- Perl isn't a toolbox, but a small machine shop where you can special-order certain sorts of tools at low cost and in short order. -- Larry Wall -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
John W. Krahn wrote: Chas Owens wrote: On 4/19/07, Jenda Krynicky [EMAIL PROTECTED] wrote: From: Chas Owens [EMAIL PROTECTED] foreach is dead, long live for. I would myself use for for the C-style loops And this is why. As long as people think well, I have foreach which is for iterating and for which is for C-style loops they will continue to write C-style loops. C-style loops are bad. They are there for backwards compatibility. I can't think of a single for loop that isn't better written as a range based for loop or while loop. For instance standard range based loop for (my $i = 0; $i 10; $i++) {} for my $i (0 .. 9) {} How about: for ( my $i = 0; $i 10; $i += 3 ) {} foreach my $i ( ? .. ? ) {} And for (my $elem = $doc-firstChild; $elem; $elem = $elem-nextSibling) { : } Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
On 4/19/07, John W. Krahn [EMAIL PROTECTED] wrote: Chas Owens wrote: Yes, foreach was aliased to for for backwards compatibility, Huh? Do you have something to back up that claim? Well, perlsyn* says The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity. (Or because the Bourne shell is more familiar to you than csh, so writing for comes more naturally.) But Synopsis 4* says There is no foreach statement any more. It's always spelled for in Perl 6, so it always takes a list as an argument So, you can either start training yourself to say for instead of foreach now or wait for culture shock down the road. but, like telnet and rsh, it should not be used in new code. Really? I assume you mean the protocols and not the programs? The protocols and the programs (unless you are using the telnet program for manual testing of server protocols). I would myself use for for the C-style loops And this is why. As long as people think well, I have foreach which is for iterating and for which is for C-style loops they will continue to write C-style loops. C-style loops are bad. They are there for backwards compatibility. I can't think of a single for loop that isn't better written as a range based for loop or while loop. For instance standard range based loop for (my $i = 0; $i 10; $i++) {} for my $i (0 .. 9) {} How about: for ( my $i = 0; $i 10; $i += 3 ) {} foreach my $i ( ? .. ? ) {} for my $i (0 .. 3) { $i *= 3; } for my $i (map { $_ * 3 } 0 .. 3) { print $i\n; } The bigger question is why is the end condition 10? Did you intend to include it the list? Are you making an off by one error? This is why the C-style for loop is bad. A better phrasing would be: my @a = (0 .. 10); for (my $i = 0; $i @a; $i += 3) { func($a[$i])} This is much harder to move away from the C-style for loop. I also can't think of the last time I needed to do it. Hmm, the naive implementation is not bad, it communicates the intent a little better in my mind, but I don't like it. my @a = (0 .. 10); my $i = 0; for my $elem (@a) { next if $i++ % 3; func($elem); } I think this solution communicates the intent best. my @a = (0 .. 10); my $i = 0; for my $elem (grep {not $i++ % 3} @a) { func($elem); } In Perl 6 we will have better options. I don't like this one, it seems too kludgey for @a - $elem, undef, undef { func($elem) } This one is only a little better than the Perl 5 variant for each(@a ; 0 .. *) - $elem, $i { next if $i % 3; func($elem) } Of course, there is the C-style for loop in disguise loop ($i = 0; $i @a; $i += 3) { func($a[$i]) } This looks the C-style for loop in disguise for 0 .. $#a : by(3) - $i { func($a[$i]) } But with a little tweak I think it is the best of all for @a[0 .. $#a : by(3)] - $elem { func($elem) } often $i winds up being used as an index which just makes me cringe. The infinite loop for (;;) {} while (1) {} The reason C programmers give for using for (;;) is that it generates less overhead on their platform, but, at least with my tests*, while(1) is more efficient in Perl. I ran your benchmark on my computer and for(;;) and while(1) ran at about the same speed. Which still proves the point, for(;;) is no better than while (1) for infinite loops. In my opinion while is better since I will eventually realize that this should not be an infinite loop. my $continue = 1; $SIG{__TERM__} = sub { $continue = 0 }; while ($continue} { } * http://perldoc.perl.org/perlsyn.html * http://dev.perl.org/perl6/doc/design/syn/S04.html -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
On 4/19/07, Rob Dixon [EMAIL PROTECTED] wrote: snip for (my $elem = $doc-firstChild; $elem; $elem = $elem-nextSibling) { : } snip I covered that in my earlier email: Weirder stuff that you only tend to see people coming from a C background do for (my $node = $head; $node;$node = $node-next) {} ... But in Perl it is rarely necessary to do this sort of loop since most functions return a list that can be iterated over using for: for my $node ($head-nodes) {} In this case your module should include a children method for my $elem ($doc-children) {} or a true iterator my $iter = $doc-child_iter; while (my $elem = $iter-next) {} If it doesn't then bug the maintainer to add one or both. Having a true iterator will put him or her ahead of the curve for Perl 6's iterated-the-iterator operator for =$iter - $elem {} -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
On 4/18/07, yitzle [EMAIL PROTECTED] wrote: I got an array of hashes so I am using a foreach (@arr) loop to access the hashes. How do I go about looping through the hash's keys/values? I was thinking of another foreach, but then the $_ gets a bit screwed up... Do I need to do this ? foreach(@arr) { %hash = %{$_}; foreach (keys %hash) { print $_ = $hash{$_}\n; } } foreach is dead, long live for. Use named values in your for loop: for my $h (@arr) { for my $key (sort keys %$h) { print $key = $h-{$key}\n } } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested loop
On 4/18/07, yitzle [EMAIL PROTECTED] wrote: I got an array of hashes so I am using a foreach (@arr) loop to access the hashes. How do I go about looping through the hash's keys/values? I was thinking of another foreach, but then the $_ gets a bit screwed up... Do I need to do this ? foreach(@arr) { %hash = %{$_}; foreach (keys %hash) { print $_ = $hash{$_}\n; } } This is a good time to avoid the foreach loop's default control variable. Although $_ is handy for small loops, larger (and nested) ones should generally name another control variable. By giving a name to the control variable, you should be able to access the hash without copying the data to another %hash variable. Perl even has special syntax you can use if the reference is in a scalar variable. It can even be a 'my' variable: my @arr = ( # just some sample hash references { qw/ fred flintstone barney rubble wilma flintstone betty rubble / }, { qw/ 4 ! 2 potato 3 potato 1 potato / }, { qw/ 4 gotten 2 cool /, '2 ', 'B' }, ); foreach my $href (@arr) { foreach (sort keys %$href) { print $_ = $href-{$_}\n; } print \n; } Hope this helps! --Tom Phoenix Stonehenge Perl Training -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Nested Loop
- Original Message - From: [EMAIL PROTECTED] Date: Thursday, January 19, 2006 3:19 pm Subject: Nested Loop Greetings, Hello Basically I deleted a portion of a mysql database and need to insert the subnet back in. The output is suppose to increment the first field starting with '8' until the IP is 10.168.17.255. I can't figure out my inside loops condition. You have a Typo Sir. Maybe there is a perl module for this? Example: INSERT INTO `anyInventory_values` VALUES (8,1,'10.168.17.0'); INSERT INTO `anyInventory_values` VALUES (8,2,'Unknown'); INSERT INTO `anyInventory_values` VALUES (8,3,''); INSERT INTO `anyInventory_values` VALUES (8,4,''); INSERT INTO `anyInventory_values` VALUES (8,5,''); INSERT INTO `anyInventory_values` VALUES (8,6,''); INSERT INTO `anyInventory_values` VALUES (8,7,''); INSERT INTO `anyInventory_values` VALUES (8,8,'Unknown'); INSERT INTO `anyInventory_values` VALUES (8,9,''); INSERT INTO `anyInventory_values` VALUES (8,10,''); INSERT INTO `anyInventory_values` VALUES (8,14,''); INSERT INTO `anyInventory_values` VALUES (9,1,'10.168.17.1'); INSERT INTO `anyInventory_values` VALUES (9,2,'Unknown'); INSERT INTO `anyInventory_values` VALUES (9,3,''); INSERT INTO `anyInventory_values` VALUES (9,4,''); INSERT INTO `anyInventory_values` VALUES (9,5,''); INSERT INTO `anyInventory_values` VALUES (9,6,''); INSERT INTO `anyInventory_values` VALUES (9,7,''); INSERT INTO `anyInventory_values` VALUES (9,8,'Unknown'); INSERT INTO `anyInventory_values` VALUES (9,9,''); INSERT INTO `anyInventory_values` VALUES (9,10,''); INSERT INTO `anyInventory_values` VALUES (9,14,''); ... My Runaway Perl Script: $file = 'out.sql'; # sql script open(INFO, $file); # open for output for($x=0;$x=255;$x++){ for($n=8;$n+1;$n++){ There is no terminated condition here, you probably wanted to say for($n=1;$n=8;$n++){ Alternative would be for my $n (1...8){ print INFO INSERT INTO \`anyInventory_values\` VALUES ($n,1,'10.168.17.$x')\;\n; print INFO INSERT INTO \`anyInventory_values\` VALUES ($n,2,'Unknown')\;\n; print INFO INSERT INTO \`anyInventory_values\` VALUES ($n,3,'')\;\n; print INFO INSERT INTO \`anyInventory_values\` VALUES ($n,4,'')\;\n; print INFO INSERT INTO \`anyInventory_values\` VALUES ($n,5,'')\;\n; print INFO INSERT INTO \`anyInventory_values\` VALUES ($n,6,'')\;\n; print INFO INSERT INTO \`anyInventory_values\` VALUES ($n,7,'')\;\n; print INFO INSERT INTO \`anyInventory_values\` VALUES ($n,8,'Unknown')\;\n; print INFO INSERT INTO \`anyInventory_values\` VALUES ($n,9,'')\;\n; print INFO INSERT INTO \`anyInventory_values\` VALUES ($n,10,'')\;\n; print INFO INSERT INTO \`anyInventory_values\` VALUES ($n,14,'')\;\n; } } -- 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: nested replace string
Please help me in where I am going wrong and suggest me the solution. Since you have the data in nice XML format, why not use an XML parser instead of parsing it yourself? http://perl-xml.sourceforge.net/faq/ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested if
No, your post was not in the last e-mail digest I received, unless I missed it somehow? But the link you provided seems to clear things up for me. So, it's not about the order of operation but the timing of when the variables actually get defined. That is, during the beginning of the loop since the values are not defined then they are ignored. When the loop proceeds again these values (at this point) are now defined because of the previous iteration of the loop has set the values from the else statement? -Mike On Jul 2, 2004, at 10:25 PM, Michael S. Robeson II wrote: Well yeah, the indentation makes it much more clearer. However, this does not help me understand how the nested if statements are working. Which of the two if statements gets evaluated first? I am trying to figure out in english what the if statements are actually doing. Is it saying: If a line begins with bla-bla and if $seq (which appears no where else in the code other than $seq= ) exists assign it to the hash pro with the name bla-bla. So my question is how does the inner if statement work when seq= is out side that if statement? Is the outer if statement evaluated first then the inner? Because how does the inner if statement know what $seq is? I am probably not making any sense but I am trying to figure out mechanically how the perl interpreter knows what to do in the context of the nested if statements. -Thanks -Mike Gunnar Hjalmarsson wrote: That illustrates the importance of indenting the code in a way that makes sense: while (align) { $line=$_; if ($line=~/^(.+)/) { if ($seq) { $pro{$name}=$seq; #print SEQ:\n$pro\n\n; } $name=$1; $name=~s/\s//g; push @names, $name; #print $name\n; $k++; $seq=; } else { chomp $line; $seq.=$line; } } Quite a difference, isn't it? -- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested if
Great, thanks for the help! -Mike On Jul 3, 2004, at 2:16 PM, Gunnar Hjalmarsson wrote: Michael S. Robeson II wrote: No, your post was not in the last e-mail digest I received, I see. Sometimes I think that digest mode for mailing lists is a nuisance. ;-) But the link you provided seems to clear things up for me. So, it's not about the order of operation but the timing of when the variables actually get defined. That is, during the beginning of the loop since the values are not defined then they are ignored. When the loop proceeds again these values (at this point) are now defined because of the previous iteration of the loop has set the values from the else statement? Yep, that's it. I would suggest that you to post the above comment to the list, too. Rgds, Gunnar -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested if
Well yeah, the indentation makes it much more clearer. However, this does not help me understand how the nested if statements are working. Which of the two if statements gets evaluated first? I am trying to figure out in english what the if statements are actually doing. Is it saying: If a line begins with bla-bla and if $seq (which appears no where else in the code other than $seq= ) exists assign it to the hash pro with the name bla-bla. So my question is how does the inner if statement work when seq= is out side that if statement? Is the outer if statement evaluated first then the inner? Because how does the inner if statement know what $seq is? I am probably not making any sense but I am trying to figure out mechanically how the perl interpreter knows what to do in the context of the nested if statements. -Thanks -Mike Gunnar Hjalmarsson wrote: That illustrates the importance of indenting the code in a way that makes sense: while (align) { $line=$_; if ($line=~/^(.+)/) { if ($seq) { $pro{$name}=$seq; #print SEQ:\n$pro\n\n; } $name=$1; $name=~s/\s//g; push @names, $name; #print $name\n; $k++; $seq=; } else { chomp $line; $seq.=$line; } } Quite a difference, isn't it? -- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested if
On 7/2/2004 10:25 PM, Michael S. Robeson II wrote: Well yeah, the indentation makes it much more clearer. However, this does not help me understand how the nested if statements are working. Which of the two if statements gets evaluated first? I am trying to figure out in english what the if statements are actually doing. Is it saying: If a line begins with bla-bla and if $seq (which appears no where else in the code other than $seq= ) exists assign it to the hash pro with the name bla-bla. So my question is how does the inner if statement work when seq= is out side that if statement? Is the outer if statement evaluated first then the inner? Because how does the inner if statement know what $seq is? I am probably not making any sense but I am trying to figure out mechanically how the perl interpreter knows what to do in the context of the nested if statements. Tidied up a little more: my( %pro, @names); my( $name, $seq, $k ); while (defined( my $line = DATA )) { if ($line =~ /^(.+)/) { if ($seq) { $pro{$name} = $seq; $seq = ''; } $name = $1; $name =~ s/\s//g; push @names, $name; $k++; } else { chomp( $line ); $seq .= $line; } } This code deals with multi-line sequences, putting multiple lines together untill a sequence is complete. The 'else' part of the outter 'if' does the accumulation of multiple lines into a sequence. The 'if' part determines that a sequence is complete, captures some type of name from the sequence, stores the complete sequence in the '%pro' hash, and pushes the name onto a '@names' array. I'm guessing '$k' keeps tally of the number of sequences; it's not clear if that is neccessary since `scalar @names` possibly will provide the same info. It's also unclear why there is a '@names' array that mostly duplicates `keys %pro` I think where you're-understandably-getting confused is that most of those variables are global. That's made more explicit in my strictified rewrite above. It could probably be rewritten better if we knew the exact format of the data being read. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested if
On 7/3/2004 4:38 AM, Randy W. Sims wrote: Tidied up a little more: Actually, I'd probably invert the condition to make it clearer that it's accumulating multi-line sequences. my( %pro, @names); my( $name, $seq, $k ); while (defined( my $line = DATA )) { unless ($line =~ /^(.+)/) { chomp( $line ); $seq .= $line; } else { if ($seq) { $pro{$name} = $seq; $seq = ''; } ($name = $1) =~ s/\s//g; push @names, $name; $k++; } } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested if
Michael S. Robeson II wrote: Which of the two if statements gets evaluated first? I am trying to figure out in english what the if statements are actually doing. Is it saying: If a line begins with bla-bla and if $seq (which appears no where else in the code other than $seq= ) exists assign it to the hash pro with the name bla-bla. So my question is how does the inner if statement work when seq= is out side that if statement? It's a while loop. For a particular iteration of the loop, $seq and $name may contain values that were assigned to them during a *previous* iteration, but the values that will be used in the inner if-statement during the *current* iteration is not related to what will happen to those variables later during this same iteration. Is the outer if statement evaluated first then the inner? As long as we are talking about the same iteration: No. Because how does the inner if statement know what $seq is? See above. HTH -- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested if
Ok, that make much more sense - I think. So, I guess, the outer 'if' and 'else' statements get evaluated first. Then the inner 'if' can proceed once all the lines of data were gathered in the outer 'else' statement. This way the lines can be assigned as a key-value pair in the hash. I guess the individual who wrote the code could make it much cleaner or easier to read. The re-organizing of the conditionals in your second e-mail makes it perfectly clear and would be something I would have done had I known how the nested 'if' statement was working (again if I have right). Hopefully, I 'got it' now. I can see why many coders are annoyed with nested if statements. :-) -Thanks! -Mike On Jul 3, 2004, at 4:38 AM, Randy W. Sims wrote: On 7/2/2004 10:25 PM, Michael S. Robeson II wrote: Well yeah, the indentation makes it much more clearer. However, this does not help me understand how the nested if statements are working. Which of the two if statements gets evaluated first? I am trying to figure out in english what the if statements are actually doing. Is it saying: If a line begins with bla-bla and if $seq (which appears no where else in the code other than $seq= ) exists assign it to the hash pro with the name bla-bla. So my question is how does the inner if statement work when seq= is out side that if statement? Is the outer if statement evaluated first then the inner? Because how does the inner if statement know what $seq is? I am probably not making any sense but I am trying to figure out mechanically how the perl interpreter knows what to do in the context of the nested if statements. Tidied up a little more: my( %pro, @names); my( $name, $seq, $k ); while (defined( my $line = DATA )) { if ($line =~ /^(.+)/) { if ($seq) { $pro{$name} = $seq; $seq = ''; } $name = $1; $name =~ s/\s//g; push @names, $name; $k++; } else { chomp( $line ); $seq .= $line; } } This code deals with multi-line sequences, putting multiple lines together untill a sequence is complete. The 'else' part of the outter 'if' does the accumulation of multiple lines into a sequence. The 'if' part determines that a sequence is complete, captures some type of name from the sequence, stores the complete sequence in the '%pro' hash, and pushes the name onto a '@names' array. I'm guessing '$k' keeps tally of the number of sequences; it's not clear if that is neccessary since `scalar @names` possibly will provide the same info. It's also unclear why there is a '@names' array that mostly duplicates `keys %pro` I think where you're-understandably-getting confused is that most of those variables are global. That's made more explicit in my strictified rewrite above. It could probably be rewritten better if we knew the exact format of the data being read. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested if
Michael S. Robeson II wrote: I came across some code on the internet that looks like this (this is only part of the script): while (align) { $line=$_; if ($line=~/^(.+)/) { if ($seq) { $pro{$name}=$seq; #print SEQ:\n$pro\n\n; } $name=$1; $name=~s/\s//g; push @names, $name; #print $name\n; $k++; $seq=; } else { chomp $line; $seq.=$line; } } I am having trouble figuring out how the nested if statements work (i.e. what is the order of operation etc...) and their associated else statements. That illustrates the importance of indenting the code in a way that makes sense: while (align) { $line=$_; if ($line=~/^(.+)/) { if ($seq) { $pro{$name}=$seq; #print SEQ:\n$pro\n\n; } $name=$1; $name=~s/\s//g; push @names, $name; #print $name\n; $k++; $seq=; } else { chomp $line; $seq.=$line; } } Quite a difference, isn't it? -- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Nested {}
On 6/29/2004 9:58 PM, David Arnold wrote: All, Suppose I have a number of lines in a latex file like this: \backans{If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can substitute to find a solution.} I'd like to scan the file and replace all of these with this format: \begin{answer} If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can substitute to find a solution. \end{answer} I'm looking for suggestions as to how to make this change with my perl script. I am puzzled by the use of nested braces and how I can be sure I've got everything between the opening and closing brace. You may want to take a look at Text::Balanced or Regexp::Common (the Regexp::Common::balanced subclass). For this type of work though, I generally prefer the more straightforward method of walking thru the file one char at a time, counting opening braces and substracting closing braces until the count reaches zero. At that point you can take the appropriate action. For this task, I really don't believe regexs offer any advantage and are probably slower (I'm sure Japhy will correct me if I'm wrong here). Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Nested {}
Japhy, Thanks. These suggestions worked great! At 01:18 AM 6/30/04 -0400, you wrote: On Jun 29, David Arnold said: \backans{If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can substitute to find a solution.} I'd like to scan the file and replace all of these with this format: \begin{answer} If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can substitute to find a solution. \end{answer} To match nested things, you probably want to use Regexp::Common, which allows you to do that very easily: use Regexp::Common; $text =~ s \\ backans { ( $RE{balanced}{-parens='{}'} ) } \\begin{answer}\n$1\n\\end{answer}xg; The /x modifier is so that I can have extra whitespace, and the /g modifier means do it globally. The %RE hash is quite magical -- see the Regexp::Common docs for an explanation. The module isn't standard, though, so you'd have to download it from CPAN yourself. If you want a stand-alone solution, you can have one if you make use of some of Perl's special regex constructs: my $rx; # must be declared first... $rx = qr[ (?: (? [^{}\\]+ | \\. ) | { (??{ $rx }) } )* ]xs; $text =~ s/\\backans{($rx)}/\\begin{answer}\n$1\n\\end{answer}/g; Its primary trick is the (??{ ... }) assertion, which evaluates its contents as PART of the regex to match. Since its contents are $rx itself, it basically creates an automatically deeply-enough nested regex for you on the fly. -- Jeff japhy Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/ RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/ CPAN ID: PINYAN[Need a programmer? If you like my work, let me know.] stu what does y/// stand for? tenderpuss why, yansliterate of course. -- 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: Nested {}
David Arnold [EMAIL PROTECTED] wrote: : Suppose I have a number of lines in a latex file like this: : : \backans{If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can : substitute to find a solution.} : : I'd like to scan the file and replace all of these with : this format: : : \begin{answer} : If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can substitute : to find a solution. : \end{answer} : : I'm looking for suggestions as to how to make this change : with my perl script. I am puzzled by the use of nested : braces and how I can be sure I've got everything between : the opening and closing brace. As long as the lines do not wrap, you don't need to worry about the nesting. Perl regexes are greedy by default. So '.+' will try to suck in the longest match possible. Which is just what you want. while ( DATA ) { printf \\begin{answer}\n%s\n\\end{answer}\n, $1 if /^\\backans{(.+)}/; } __END__ \backans{If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can ...} \backans{If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can ...} \backans{If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can ...} \backans{If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can ...} HTH, Charles K. Clarkson -- Mobile Homes Specialist 254 968-8328 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
RE: Nested {}
Charles, Very nice indeed. I learned a lot with your example. Unfortunately, there are a lot of situations where the lines wrap. For example, \backans{Now is the time for all good men to come to the aid of their country. The domain of $f(x)=\sqrt{2x+3}$ is $\{x:\,x\ge -3/2\}$.} Do you have similar good advice for the wrapping situation? At 09:18 PM 6/29/04 -0500, Charles K. Clarkson wrote: David Arnold [EMAIL PROTECTED] wrote: : Suppose I have a number of lines in a latex file like this: : : \backans{If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can : substitute to find a solution.} : : I'd like to scan the file and replace all of these with : this format: : : \begin{answer} : If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can substitute : to find a solution. : \end{answer} : : I'm looking for suggestions as to how to make this change : with my perl script. I am puzzled by the use of nested : braces and how I can be sure I've got everything between : the opening and closing brace. As long as the lines do not wrap, you don't need to worry about the nesting. Perl regexes are greedy by default. So '.+' will try to suck in the longest match possible. Which is just what you want. while ( DATA ) { printf \\begin{answer}\n%s\n\\end{answer}\n, $1 if /^\\backans{(.+)}/; } __END__ \backans{If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can ...} \backans{If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can ...} \backans{If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can ...} \backans{If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can ...} HTH, Charles K. Clarkson -- Mobile Homes Specialist 254 968-8328 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Nested {}
On Jun 29, David Arnold said: \backans{If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can substitute to find a solution.} I'd like to scan the file and replace all of these with this format: \begin{answer} If $x=y^{2n}$ and $z=y^{3n}_{11}$, then we can substitute to find a solution. \end{answer} To match nested things, you probably want to use Regexp::Common, which allows you to do that very easily: use Regexp::Common; $text =~ s \\ backans { ( $RE{balanced}{-parens='{}'} ) } \\begin{answer}\n$1\n\\end{answer}xg; The /x modifier is so that I can have extra whitespace, and the /g modifier means do it globally. The %RE hash is quite magical -- see the Regexp::Common docs for an explanation. The module isn't standard, though, so you'd have to download it from CPAN yourself. If you want a stand-alone solution, you can have one if you make use of some of Perl's special regex constructs: my $rx; # must be declared first... $rx = qr[ (?: (? [^{}\\]+ | \\. ) | { (??{ $rx }) } )* ]xs; $text =~ s/\\backans{($rx)}/\\begin{answer}\n$1\n\\end{answer}/g; Its primary trick is the (??{ ... }) assertion, which evaluates its contents as PART of the regex to match. Since its contents are $rx itself, it basically creates an automatically deeply-enough nested regex for you on the fly. -- Jeff japhy Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/ RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/ CPAN ID: PINYAN[Need a programmer? If you like my work, let me know.] stu what does y/// stand for? tenderpuss why, yansliterate of course. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested foreach not looping properly
Mike Re-V wrote: The following code iterates unexpectedly. I want to loop thru the file 'file.dat' and pull out every field that begins with 650. The code then pulls the 650 field and builds an array from the sub-fields. The code works but I'm stuck on the first record. In other words if the file I'm reading has 2000 records I get the first 650 record 2000X use MARC::Batch; my $batch =MARC::Batch-new('USMARC','file.dat'); my $record = $batch-next(); ## get all the 852 fields (list context). my @fields = $record-field('852'); ## examine each 852 field and print it out. while (my $record = $batch-next()) { foreach my $field (@fields) { print $field-as_string(),\n; } } I don't know anything about the MARC::Batch module, but I notice that the foreach loop is running independently from variables set in the while() loop. Consequently, it does not surprise me when you say that you are stuck. Btw, why don't you enable strictures and warnings? -- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested parens
Let's test it. use strict; use warnings; use Data::Dumper 'Dumper'; foreach my $string ( '(foo) (bar)', '(foo) (bar) (baz)', '((foo) bar)) (baz)', '(foo bar)',) { my @text_inside_parens = $string =~ m/\((.*)\)/g; print Dumper [EMAIL PROTECTED]; } __END__ I get: $VAR1 = [ 'foo) (bar' ]; $VAR1 = [ 'foo) (bar) (baz' ]; $VAR1 = [ '(foo) bar)) (baz' ]; $VAR1 = [ 'foo bar' ]; .* is greedy. I suspect @text_inside_parens will never have more than one element in it. Right, The point was, regexes could help, I never said it wasn't greedy or the example was 100% what he needed, just a suggestion for another place to start looking :) (I figured it was a *little* better than `perldoc perlre` ;p) Thanks for taking the time to do that example. Lee.M - JupiterHost.Net HTH, Charles K. Clarkson -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested parens
Charles K. Clarkson wrote: JupiterHost.Net [EMAIL PROTECTED] wrote: : : [EMAIL PROTECTED] wrote: : Is there a module out there that I can use to parse : a text line and return the pieces that are enclosed : in paren's? : : You don't need a module for that just use regex's: : : my @text_inside_parens = $string =~ m/\((.*)\)/g; Let's test it. use strict; use warnings; use Data::Dumper 'Dumper'; foreach my $string ( '(foo) (bar)', '(foo) (bar) (baz)', '((foo) bar)) (baz)', '(foo bar)',) { my @text_inside_parens = $string =~ m/\((.*)\)/g; print Dumper [EMAIL PROTECTED]; } __END__ I get: $VAR1 = [ 'foo) (bar' I see. Someone dun fergot the lazy symbol, huh? ... .* is greedy. I suspect @text_inside_parens will never have more than one element in it. good point. ... my @text_inside_parens = $string =~ m/\((.*?)\)/g; print Dumper [EMAIL PROTECTED]; } __END__ $VAR1 = [ 'foo', 'bar' ]; $VAR1 = [ 'foo', 'bar', 'baz' ]; ... Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested parens
Let's test it. use strict; use warnings; use Data::Dumper 'Dumper'; foreach my $string ( '(foo) (bar)', '(foo) (bar) (baz)', '((foo) bar)) (baz)', '(foo bar)',) { my @text_inside_parens = $string =~ m/\((.*)\)/g; print Dumper [EMAIL PROTECTED]; } __END__ I get: $VAR1 = [ 'foo) (bar' ]; $VAR1 = [ 'foo) (bar) (baz' ]; $VAR1 = [ '(foo) bar)) (baz' ]; $VAR1 = [ 'foo bar' ]; .* is greedy. I suspect @text_inside_parens will never have more than one element in it. Right, The point was, regexes could help, I never said it wasn't greedy or the example was 100% what he needed, just a suggestion for another place to start looking :) (I figured it was a *little* better than `perldoc perlre` ;p) To illustrate further try: perl -e 'my $str = (hi)((bye)j(hi))(sweet);my @m = $str =~ m/\(([^(^).]*)\)/g; for(@m) { print -$_-\n; }' See? No module, lots of regex :) Again, maybe not exactly what they needed (IE It misses the middle 'j')but an illustration of an idea. And so everyone who is playing along at home: #!/usr/bin/perl use strict; use warnings; use Data::Dumper 'Dumper'; foreach my $string ( '(foo) (bar)', '(foo) (bar) (baz)', '((foo) bar)) (baz)', '(foo bar)',) { my @text_inside_parens = $string =~ m/\(([^(^).]*)\)/g; print Dumper [EMAIL PROTECTED]; } HTH Lee.M - JupiterHost.Net Thanks for taking the time to do that example. Lee.M - JupiterHost.Net HTH, Charles K. Clarkson -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested parens
[EMAIL PROTECTED] wrote: Is there a module out there that I can use to parse a text line and return the pieces that are enclosed in paren's? You don't need a module for that just use regex's: my @text_inside_parens = $string =~ m/\((.*)\)/g; HTH Lee.M - JupiterHost.Net 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: nested parens
JupiterHost.Net [EMAIL PROTECTED] wrote: : : [EMAIL PROTECTED] wrote: : Is there a module out there that I can use to parse : a text line and return the pieces that are enclosed : in paren's? : : You don't need a module for that just use regex's: : : my @text_inside_parens = $string =~ m/\((.*)\)/g; Let's test it. use strict; use warnings; use Data::Dumper 'Dumper'; foreach my $string ( '(foo) (bar)', '(foo) (bar) (baz)', '((foo) bar)) (baz)', '(foo bar)',) { my @text_inside_parens = $string =~ m/\((.*)\)/g; print Dumper [EMAIL PROTECTED]; } __END__ I get: $VAR1 = [ 'foo) (bar' ]; $VAR1 = [ 'foo) (bar) (baz' ]; $VAR1 = [ '(foo) bar)) (baz' ]; $VAR1 = [ 'foo bar' ]; .* is greedy. I suspect @text_inside_parens will never have more than one element in it. HTH, Charles K. Clarkson -- Mobile Homes Specialist 254 968-8328 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested parens
[EMAIL PROTECTED] wrote: Is there a module out there that I can use to parse a text line and return the pieces that are enclosed in paren's? Yep, a core module name Text::Balanced. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
RE: nested parens
thanks -Original Message- From: Randy W. Sims [mailto:[EMAIL PROTECTED] Sent: Friday, April 02, 2004 5:24 PM To: ewalker Cc: [EMAIL PROTECTED] Subject: Re: nested parens [EMAIL PROTECTED] wrote: Is there a module out there that I can use to parse a text line and return the pieces that are enclosed in paren's? Yep, a core module name Text::Balanced. Randy. 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: nested while loops using DBI
On Mon, 2004-03-22 at 18:04, Guay Jean-Sbastien wrote: Hello Mike, $row=$dbh-prepare(SELECT contact_id,first_name,last_name,organisation FROM tb_contacts WHERE organisation ILIKE ?); [...] while(($id,$first_name,$last_name,$organisation) = $row-fetchrow_array()) { [...] $row=$dbh-prepare(SELECT id,contact_id,type_of_contact,priority FROM tb_contact_role WHERE contact_id ILIKE ?); [...] } [...] This only produces on record at the top-level, if I dont have the select inside the loop, then all matching records appear Anyone any idea where I am going wrong You are using the same variable as the statement handle for both queries ($row). In effect, since your second SELECT probably returns only one row (probably the detail of the contact you got in the first SELECT), the enclosing while ends afterwards because there are no more rows to get from that statement handle (the second SELECT). Yeah I worked this out just after I posted. I would suggest you declare a new variable inside your while, say $contact. Something like this: my $contact = $dbh-prepare(qq[SELECT id, contact_id, type_of_contact, priority FROM tb_contact_role WHERE contact_id ILIKE ?]); I also suggest better indentation and whitespace usage in your code. That will get very hard to read very fast... Hope that helps, J-S -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
RE: nested while loops using DBI
Hello Mike, $row=$dbh-prepare(SELECT contact_id,first_name,last_name,organisation FROM tb_contacts WHERE organisation ILIKE ?); [...] while(($id,$first_name,$last_name,$organisation) = $row-fetchrow_array()) { [...] $row=$dbh-prepare(SELECT id,contact_id,type_of_contact,priority FROM tb_contact_role WHERE contact_id ILIKE ?); [...] } [...] This only produces on record at the top-level, if I dont have the select inside the loop, then all matching records appear Anyone any idea where I am going wrong You are using the same variable as the statement handle for both queries ($row). In effect, since your second SELECT probably returns only one row (probably the detail of the contact you got in the first SELECT), the enclosing while ends afterwards because there are no more rows to get from that statement handle (the second SELECT). I would suggest you declare a new variable inside your while, say $contact. Something like this: my $contact = $dbh-prepare(qq[SELECT id, contact_id, type_of_contact, priority FROM tb_contact_role WHERE contact_id ILIKE ?]); I also suggest better indentation and whitespace usage in your code. That will get very hard to read very fast... Hope that helps, J-S -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested Paren's
Eric Walker wrote: Hey all, I have a file with some data that has like nested parens.. example yes( hello goodbye ( (one 2) (two 3) (three 4) ) (( mon 1) (tues 2) (wed 3) ) ((jan 1) (feb 2) (march 3) ) ) I need help in trying to break this up and make key value pairs out of the data example: KEYVALUE one 2 two 3 three4 mon 1 tues 2 wed 3 jan 1 feb 2 march 3 there are many ways of doing that, here is one: #!/usr/bin/perl -w use strict; (my $parens=PARENS) =~ s/\n//g; (one 2) (two 3) (three 4) ) ((mon 1) (tues 2) (wed 3) ) ((jan 1) (feb 2) (march 3) ) PARENS my %hash = map split, $parens =~ /\(+([^()]+)\)+/g; while(my($name,$value) = each %hash){ print $name,$value\n; } __END__ prints: feb,2 jan,1 three,4 march,3 one,2 mon,1 wed,3 tues,2 two,3 depends on the actual data you have, you might need to modify the above slightly to suit your case. another way of doing it is to remove the parens and replace multiple spaces with one and then split on a single space to get the name value pair you want but this approach is slightly less efficient than the proposed one. it's, however, a bit easier to code. david -- s,.*,,e,y,\n,,d,y,.s,10,,s .ss.s.s...s.sss.s.ss s.s.s...s...s..s ...s.ss..s.sss..ss.sss.s s.s.s...ss.sss.s ..s..sss.s.ss.sss... ..ssss.sss.sss.s ,{4},|?{*=}_'y!'+0!$; ,ge,y,!#:$_(-*[./[EMAIL PROTECTED],b-t, .y...,$~=q~=?,;^_#+?{~,,$~=~ y.!-*-/:[EMAIL PROTECTED] ().;s,;, );,g,s,s,$~s,g,y,y,%,,g,eval -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested Paren's
On Dec 11, 2003, at 9:30 AM, Eric Walker wrote: [..] yes( hello goodbye ( (one 2) (two 3) (three 4) ) (( mon 1) (tues 2) (wed 3) ) ((jan 1) (feb 2) (march 3) ) ) [..] The question of course is whether that 'ordering' is important, or can you just use a hash? IF you do not really need to know about the paren count then don't count it. IF you know that your generalized date is going to be of the form (word num) then your word_num regEx would look like my $word_num = qr/\( # our opening paren (\w+)\s+(\d+) \)/ix; # our closing paren I use the 'x' option to lay it out pretty like that. then the rest is a walker while ( INFO1 ) { chomp; next if (/^\s*$/); # no need empty lines s/^\s+//; # kill leaing lines my $line = $_; # now we have a line to play with while ( $line =~ /$word_num(.*)/) { $hash{$1} = $2; # our $word_num pattern fetched these $line = $3; # for everything else there is (.*) } } while (my ($k, $v) = each %hash) { print $k - $v\n; } ciao drieux --- -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested Paren's
Well, the problem is that this is just one section of a file the other sections actualy have different format. When I get to this section I key on the section name to know how to process it and will need to key on the last paren know that this section is done and to try and key on what the next section is and how it is processed. Not all of the data in this section is of the form mon 1 every know and then you get something like list( one two). The data i am making up as I didn't think it was important. I figured the form is what was needed. Once I get the key value pairs it doesn't matter because I am going to read another file like this and compare the data to make sure nothing has changed between the two files. I like the regx thing tho, it gives me some ideas.. I will see if I can make it work with that... perl knucklehead On Thu, 2003-12-11 at 11:28, drieux wrote: On Dec 11, 2003, at 9:30 AM, Eric Walker wrote: [..] yes( hello goodbye ( (one 2) (two 3) (three 4) ) (( mon 1) (tues 2) (wed 3) ) ((jan 1) (feb 2) (march 3) ) ) [..] The question of course is whether that 'ordering' is important, or can you just use a hash? IF you do not really need to know about the paren count then don't count it. IF you know that your generalized date is going to be of the form (word num) then your word_num regEx would look like my $word_num = qr/\( # our opening paren (\w+)\s+(\d+) \)/ix; # our closing paren I use the 'x' option to lay it out pretty like that. then the rest is a walker while ( INFO1 ) { chomp; next if (/^\s*$/); # no need empty lines s/^\s+//; # kill leaing lines my $line = $_; # now we have a line to play with while ( $line =~ /$word_num(.*)/) { $hash{$1} = $2; # our $word_num pattern fetched these $line = $3; # for everything else there is (.*) } } while (my ($k, $v) = each %hash) { print $k - $v\n; } ciao drieux --- -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested Paren's
Ok,, back to some laymen terms hehe... The file is read by an application and what I am doing is this. The application use to read this file that was created by hand to set some internal settings. I a wrote a program to pull the same info from a database. The auto generated file will ultimately be use for the program to read and set these internal values. I am trying to dump the current values from the program and do a compare between the file I auto created and whats in the program now. this is why I am trying to suck in all the values so I can do a compare and make sure the auto generated file does the same things as the current file that was made by hand. So the keys Idea is a no go. I am glad at least the data was good enough for us to kick around. The way they are writting is the only way they can be do to the application that reads them. How do you determine if an application has a portable library? I know nothing of that but sounds like something neat and witty.. If I could do that and use a perl module that would be nice. perlknucklehead I know nothing of xml I am sorry to say. you kinda dove off of the big diving board and I am still back putting on my floaters. hehehe... On Thu, 2003-12-11 at 12:39, drieux wrote: On Dec 11, 2003, at 10:52 AM, Eric Walker wrote: Well, the problem is that this is just one section of a file the other sections actualy have different format. [..] every know and then you get something like list( one two). [..] The data i am making up as I didn't think it was important. I figured the form is what was needed. [..] Once I get the key value pairs it doesn't matter because I am going to read another file like this and compare the data to make sure nothing has changed between the two files. [..] p0: the 'data' that you made up, was good enough to get us some direction to start looking at solutions. p1: You might ultimately want to look at a re-write of how those 'files' are being created, so that the sub-sequent post parsing is simpler. IF that is not an option - then you might want to see if the application that created the format has a library that can be 'ported' and hence build out a perl module of your own that would share it's parser structure. p1.1 - either go with say an xml-ish model hence use the LibXml module for parsing p1.2 - assume that the applications library is lib_fung_parser.so - then you want to get your hands on the header files and use h2xs to generate your Fung::Parser module p2: The problem of multiple section readings from a file should lead you towards a simpler process where you have keys in the file that indicate which 'parser' to be using at which point you might want to look at a 'dispatcher'... where each 'function' knows how\ to return stuff related to what it knows how to read, and specifically how it's 'end of section' will tell it to stop parsing and go back. ciao drieux --- -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested Paren's
On Dec 11, 2003, at 12:16 PM, Eric Walker wrote: Ok,, back to some laymen terms hehe... not sure I can do that, but hey, I'll try anything once... it seems that the two issues are a. Parser Mechanics b. File Format. The file is read by an application and what I am doing is this. The application use to read this file that was created by hand to set some internal settings. The first question is who wrote the application, and, well, to be polite, did the application writer share the parser code the it is using to read the file. But we will get back to this... for the sake of argument let's assume the simpler myApp -f config_file and myApp parses the config_file and set's it's internal values. { yes, the myApp could be reading some 'default config file', 'user preferance files', what ever - there exists some file let us call it the 'config_file' that will be read to configure the application . } [..] I am trying to dump the current values from the program and do a compare between the file I auto created and whats in the program now. There exists some 'signal' or 'messaging' method that will tell myapp: woof your current configuration data into a file { woof - technical term denoting, to heave up the foo.. } [..] So the keys Idea is a no go. I am glad at least the data was good enough for us to kick around. The way they are writting is the only way they can be do to the application that reads them. Actually what you will want to step into is the notion of 'subs' - cf perldoc perlsub, and you can 'abstract' the 'grovel_woof_file()' so that it will return you a hash. eg: suf grovel_woof_file { my ($filename) = @_; # return undefined if we can not read the file. return undef unless (-r $filename ); # steal from dzhuo[at]looksmart.net (David) open(FD, $filename) or die unable to open $filename :$!; my $parens; $parens .= $_ while(FD); # read in the file close(FD); # cf perdoc map - and thank david. my %hash = map split, $parens =~ /\(+([^()]+)\)+/g; \%hash; # return hash ref } { Yes, I know, that will ultimately need to be grown out a bit to deal with the 'variations' in the 'configuration file' as noted previously... } then you could do say my $def_hash = grovel_woof_file($default_file); make_myApp_woof($new_file); # function to make running myApp Woof... my $new_hash = grovel_woof_file($new_file); foreach my $key ( keys %$def_hash ) { if ( exists($new_hash-{$key})) { if ( $new_hash-{$key} eq $def_hash-{$key}) { print have same key $key\n; } else { whine(new key value, $key, $new_hash-{$key}); } } else { whine(no key value, $key, $def_hash-{$key}); } } we leave the whine() function to you as an exercise to whine about. { we will serve no whine() before it's time... } How do you determine if an application has a portable library? well it is less about being 'portable' in terms of being able to run on more than one os - as much as it is about exposing the parser complex that the application is using. WARNING: drieuxishSoapBoxMoment drieuxishSoapBoxMoment Files do not Just GROW in File Systems! There exists some 'code foo' that creates it, normally because there is some 'parser foo' that will read it into applications to set configuration information. Writers of Configuration File Parsers SHOULD be polite and offer up access to their Configuration File Parsing routines so that they can be exposed in other languages, such as Perl, so that the support crew can be more effective! App Writers who create WACKO configuration file stuff so as to create Wacko Configuration File Parsers that they are not willing to share with their support crew are building up bad kharma, and the BadKharmaFerrie Will Get them at PayBack! /drieuxishSoapBoxMoment { I feel better now. } I know nothing of that but sounds like something neat and witty.. If I could do that and use a perl module that would be nice. what you will want to learn down that path is perldoc h2xs perldoc perlmodlib and specifically you will want to pick up learning Perl Objects, References and Modules, as well as the 3rd Edition of Programming perl... perlknucklehead I know nothing of xml I am sorry to say. you kinda dove off of the big diving board and I am still back putting on my floaters. hehehe... sorry, that Must have been my evil twin Skippy ciao drieux -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Nested quantifiers error?
On Oct 17, Michael Weber said: When I try to find out what the spam score is I am getting a weird error. It's not that weird an error. Perl is telling you exactly what's wrong, exactly where it's wrong. if ( $msg[$line] =~ '^X-Spam-Level: ***' ) { $bad_spam += 1; } Nested quantifiers before HERE mark in regex m/^X-Spam-Level: ** HERE */ at /home/filter/grab.pl line 16. Why am I getting a HERE marker? Do I need to escape all the *s? Do I need to do something else? The HERE is telling you where in the regex the problem is. The problem is that '*' is a regex metacharacter. Just because your regex is in single quotes (not a smart idea, because it's misleading) doesn't mean that it's NOT a regex. $bad_spam++ if $msg[$line] =~ /^X-Spam-Level: \*{11}/; -- Jeff japhy Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/ RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/ stu what does y/// stand for? tenderpuss why, yansliterate of course. [ I'm looking for programming work. If you like my work, let me know. ] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested anonymous reference syntax
[EMAIL PROTECTED] wrote: Hello, I'm having trouble grasping the syntax to perform foreach operation on an anonymous array within an anonymous hash reference. my $hashRef = { bah = humbug, list = [ lions, tigers, bears, oh_my ], woo = hoo }; here you have a hash ref named $hashRef How can I run a foreach on every item in that anonymous array reference that is a value of the key list in the hash reference? I'm having great difficulties getting this to work. Is it even possible without nested foreach structures? I would think it would be something like: foreach my $listItem (@{$hashref{list}}) { print $_list item is one item of the array! Woo hoo!\n; } here you are trying to access the 'list' slot of a hash named $hashref which on course is different than $hashRef you declared above. not to mention that you are not treating $hashref as hash reference, you are using it as a hash. which one is it? is $hashref really a hash reference or just a hash? is $hashRef the same as $hashref? if $hashref is the same as $hashRef and it's really a hash reference, try: for(@{$hashRef-{list}}){ print $_\n; } if $hashref is NOT the same as $hashRef and it's really just a hash, you have the right syntax: for(@{$hashref{list}}){ print $_\n; } david -- $_=q,015001450154015401570040016701570162015401440041,,*,=*|=*_,split+local$; map{~$_1{$,=1,[EMAIL PROTECTED]||3])=~}}0..s~.~~g-1;*_=*#, goto=print+eval -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested anonymous reference syntax
[EMAIL PROTECTED] wrote: I'm having trouble grasping the syntax to perform foreach operation on an anonymous array within an anonymous hash reference. my $hashRef = { bah = humbug, list = [ lions, tigers, bears, oh_my ], woo = hoo }; How can I run a foreach on every item in that anonymous array reference that is a value of the key list in the hash reference? I'm having great difficulties getting this to work. Is it even possible without nested foreach structures? I would think it would be something like: foreach my $listItem (@{$hashref{list}}) { print $_list item is one item of the array! Woo hoo!\n; } But, that does not work. I know this works: foreach my $item (${$hashRef}{list}) { foreach (@$item) { print $_\n; } } But, that seems like a lot of unnecessary work, iteration, and typing. I would appreciate any help. Thanks in advance! :) Hi Chris. Very nearly right, but its foreach my $listItem (@{$hashref{list}}) { print $listItem is one item of the array! Woo hoo!\n; } OR foreach (@{$hashref{list}}) { print $_ is one item of the array! Woo hoo!\n; } HTH, Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested parenthesis in regex and launching a new process
On Tuesday, September 2, 2003, at 11:51 PM, Bryan Harris wrote: Thanks for the info, James. Sounds like threading is still a ways over my head, but forking sounds interesting. I have a perl script that does simple find-replaces within all the files passed to it (the key parts were written by very kind people on this list, actually). Would it be advantageous for the script to fork so that it could be find-replacing on all files simultaneously as opposed to serially? I seriously doubt it. It's usually a bad idea to make anything more complicated than strictly needed. Multiprocessing is a lot of work, mostly because you have to control how information is shared between the two processes/threads. For example, even in a simple find and replace script, each part would have to know which files were being handled by the other processes/threads. Save forking and threading for when you absolutely must do two or more things at once, say in servers, complex GUIs, etc. Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested parenthesis in regex and launching a new process
I seriously doubt it. It's usually a bad idea to make anything more complicated than strictly needed. Multiprocessing is a lot of work, mostly because you have to control how information is shared between the two processes/threads. For example, even in a simple find and replace script, each part would have to know which files were being handled by the other processes/threads. Save forking and threading for when you absolutely must do two or more things at once, say in servers, complex GUIs, etc. Thanks, James. - Bryan -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested parenthesis in regex and launching a new process
ZSDC, I love this stuff! You explain these concepts very clearly, have you ever considered teaching? I'm happy to keep asking questions as long as you're willing to answer them. =) Servers often work this way. There's a process listening on a port but when someone connects, it doesn't serve the actual request (which would block the server and no one else could connect until it's done) but only forks the child, which then serves the request, and the parent keeps listening for another requests and forks another children at the same time. Neat! Is this how threads are spawned? or are forked processes different from threads? If this is how threads are spawned, how do big commercial apps manage to do multiple things at once without completely duplicating the entire executable in RAM? or is Perl's implementation less robust than the one used for C++-type apps? As for the client side, you could for example have a mail client downloading mail in the background, while the user can keep writing and sending mail at the same time, etc. Check out this example: #!/usr/bin/perl -w open F, '+', $0-result or die $!; What is '+'? I've never seen that before. defined(my $pid = fork) or die $!; unless ($pid) { # child: sleep 5; # an important time consuming task... print F 123\n; exit; } # parent: print Not yet... Do something else.\n and sleep 1 until -s F; I haven't seen the '-s F' notation either -- is it a -x file test? Yes. Actually, there's a whole genealogy tree. The process with ID 1 (usually called init) is the protoplast of every other process running on the system. This is the only process without a parent. The killing of children makes sense when e.g. I open an xterm window and run man fork. What I have now is a shell process which is a child of xterm, a man process which is a child of the shell and a pager (for scrolling man's output) which is a child of man. Now, when I just close the xterm window, the pager, man and shell are killed as well. It makes sense, because keeping them running (sleeping, actually) would be pointless. This is all starting to make sense now... Thank you! But sometimes you don't want that. For example, your ssh connection could die, everything is killed and you have to connect and login once again and start everything from the beginning. If you don't want that, then check out this great little program: Once you background a run in a shell, though, it seems to keep running, at least on our SGIs. How does that work? For example, I set a complex model running with: % itods myfile.txt Now if I exit the shell, the process keeps going. How does that fit in? What is a session? I've never heard of that... A session is basically (it's an oversimplification) a bunch of processes which get killed if you close the session, because they are important only for that session (like the example with xterm). For more informations see: man setsid http://linux.ctyme.com/man/man2993.htm man getsid http://linux.ctyme.com/man/man0960.htm man setpgid http://linux.ctyme.com/man/man2984.htm Nice! I'm glad I could be helpful. This subject usually causes lots of confusion. I hope others could also find it interesting and didn't mind if I was a little bit off topic. Thanks again. - Bryan -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested parenthesis in regex and launching a new process
On Friday, August 29, 2003, at 01:32 AM, Bryan Harris wrote: Neat! Is this how threads are spawned? or are forked processes different from threads? If this is how threads are spawned, how do big commercial apps manage to do multiple things at once without completely duplicating the entire executable in RAM? or is Perl's implementation less robust than the one used for C++-type apps? Forking a process and threads are two different things actually. Forking makes a copy of the running process. From there, the parent and child processes can do separate things. Threading is using different streams of execution. There's only one process there, but it's doing multiple things internally. Really, they're two different ways to solve the same problem. Traditionally, forking was the UNIX way to handle this, while a lot of other platforms preferred threading. Today, you usually have both options available to you in most cases. (Windows doesn't generally support forking, but Perl on Windows does with heavy magic.) Personally, I find forking a little easier to setup and follow. As you noted though, copying the entire process is a less than ideal use of resources, so threading is generally a little more robust, for most things. Going back to servers as an example, forking works out pretty well for a web server that just needs to hand incoming requests the page they asked for (oversimplified a little). However, forking a chat server would generally be a bad idea, in my opinion. Once you had 50 users talking to each other, you would have 50 copies of all the state information the server tracks. Threading would server better here. (Technically, you can do both of the above with Non-Blocking I/O as well, eliminating the need to fork or thread. That's significantly harder though and off topic for this discussion.) As a final detail, you will probably need to compile your own version of Perl if you want to use its threading options. Hope that clears some things up. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested parenthesis in regex and launching a new process
Thanks for the info, James. Sounds like threading is still a ways over my head, but forking sounds interesting. I have a perl script that does simple find-replaces within all the files passed to it (the key parts were written by very kind people on this list, actually). Would it be advantageous for the script to fork so that it could be find-replacing on all files simultaneously as opposed to serially? Thanks again... - Bryan -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested parenthesis in regex and launching a new process
The fork concept can be quite confusing at first, but it is actually quite simple, once you get used to it. Check out the output of this little program: [ very interesting stuff cut out ] Wild! Why would anyone ever use this? Why would you ever want to clone yourself at the current point and have both continue on running? I guess I could see it being a smooth way to process a hundred files all at once (sort-of)... I don't get it. [ more interesting stuff cut out ] with '' your program won't wait for the other-program to finish, but the other-program process will die when your program (the parent process) finishes. Why is this? Does that mean if I create a new tcsh shell, run an app, kill the tcsh shell before the app finishes, that the app will die too? Why have parent/child relationships in processes? Are there such things as grandchildren/grandparents? Of course you want your program to finish without killing the child processes in the process (pun definitely intended) and for that you need your child processes to create new sessions with setsid(). What is a session? I've never heard of that... You can take a look at Proc::Daemon module on CPAN, but it's not exactly what you need, mostly because it redirects STDOUT to /dev/null, while you want your processes to write to STDOUT (by the way, are you sure about that? it can result in a total mess printed on your terminal) but still you may want to read its source to see how it works: http://search.cpan.org/src/EHOOD/Proc-Daemon-0.03/Daemon.pm Yes, I absolutely want all output going to STDOUT. Thanks for foreseeing a potential problem, though... use POSIX 'setsid'; sub forkrun ($) { my $cmd = pop; defined(my $pid = fork) or die $0: fork: $!\n; unless ($pid) { setsid or die $0: setsid: $!\n; exec $cmd; } return $pid; } Yes! This works terrifically! How does the fork part work within subroutines? I'm guessing the part starting with unless looks to see if it's now a child process, and if so, to quit the current perl script and start off $cmd. Is that right? It works, so that part's taken care of. Now I just have to figure out how it works. =) Thanks a lot zsdc. - Bryan -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested parenthesis in regex and launching a new process
Bryan Harris wrote: The fork concept can be quite confusing at first, but it is actually quite simple, once you get used to it. Check out the output of this little program: [ very interesting stuff cut out ] Wild! Why would anyone ever use this? Why would you ever want to clone yourself at the current point and have both continue on running? I guess I could see it being a smooth way to process a hundred files all at once (sort-of)... I don't get it. Servers often work this way. There's a process listening on a port but when someone connects, it doesn't serve the actual request (which would block the server and no one else could connect until it's done) but only forks the child, which then serves the request, and the parent keeps listening for another requests and forks another children at the same time. As for the client side, you could for example have a mail client downloading mail in the background, while the user can keep writing and sending mail at the same time, etc. Check out this example: #!/usr/bin/perl -w open F, '+', $0-result or die $!; defined(my $pid = fork) or die $!; unless ($pid) { # child: sleep 5; # an important time consuming task... print F 123\n; exit; } # parent: print Not yet... Do something else.\n and sleep 1 until -s F; seek F, 0, 0; print Done! The result is , F; It could be written better with pipes, or real temp files, but it's cleaner that way. The child could do something more interesting than sleeping, like downloading a webpage from a slow server, without totally freezing our program. The parent might decide to wait only ten seconds and then give up, or try again downloading from another mirror, etc. Instead of one process, you can have few processes running simultaneously and interacting with each other, while every one of them is a different incarnation of the same program. It can be very powerful. [ more interesting stuff cut out ] with '' your program won't wait for the other-program to finish, but the other-program process will die when your program (the parent process) finishes. Why is this? Does that mean if I create a new tcsh shell, run an app, kill the tcsh shell before the app finishes, that the app will die too? Why have parent/child relationships in processes? Are there such things as grandchildren/grandparents? Yes. Actually, there's a whole genealogy tree. The process with ID 1 (usually called init) is the protoplast of every other process running on the system. This is the only process without a parent. The killing of children makes sense when e.g. I open an xterm window and run man fork. What I have now is a shell process which is a child of xterm, a man process which is a child of the shell and a pager (for scrolling man's output) which is a child of man. Now, when I just close the xterm window, the pager, man and shell are killed as well. It makes sense, because keeping them running (sleeping, actually) would be pointless. But sometimes you don't want that. For example, your ssh connection could die, everything is killed and you have to connect and login once again and start everything from the beginning. If you don't want that, then check out this great little program: http://www.gnu.org/software/screen/ It's truely amazing. Of course you want your program to finish without killing the child processes in the process (pun definitely intended) and for that you need your child processes to create new sessions with setsid(). What is a session? I've never heard of that... A session is basically (it's an oversimplification) a bunch of processes which get killed if you close the session, because they are important only for that session (like the example with xterm). For more informations see: man setsid http://linux.ctyme.com/man/man2993.htm man getsid http://linux.ctyme.com/man/man0960.htm man setpgid http://linux.ctyme.com/man/man2984.htm You can take a look at Proc::Daemon module on CPAN, but it's not exactly what you need, mostly because it redirects STDOUT to /dev/null, while you want your processes to write to STDOUT (by the way, are you sure about that? it can result in a total mess printed on your terminal) but still you may want to read its source to see how it works: http://search.cpan.org/src/EHOOD/Proc-Daemon-0.03/Daemon.pm Yes, I absolutely want all output going to STDOUT. Thanks for foreseeing a potential problem, though... Instead of /dev/null you could also redirect STDOUT to real files (or pipes or sockets or whatever), so you could capture and access it without all the mess on your screen. use POSIX 'setsid'; sub forkrun ($) { my $cmd = pop; defined(my $pid = fork) or die $0: fork: $!\n; unless ($pid) { setsid or die $0: setsid: $!\n; exec $cmd; } return $pid; } Yes! This works terrifically! Great. How does the fork part work within subroutines? I'm guessing the part starting with unless looks to
Re: nested parenthesis in regex and launching a new process
Bryan Harris wrote: ... which seems to work (correctly returns file_3.1.1), but I'm not sure how the nested parenthesis are supposed to be referenced. How would I get what was matched by the inner set? Is this the best way to do this? Everything is captured in $1, $2, $3... in the order of opening parenthesis, from left to right. 2. How do I set off a new process, not waiting or caring about any return values? $myApp = /proj/mycoolexecutable; $myOptions = -f -n2 file1 file2; # execute $myApp. .$myOptions here, and do not wait for any return values See: perldoc -f fork perldoc -f exec -zsdc. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested parenthesis in regex and launching a new process
2. How do I set off a new process, not waiting or caring about any return values? $myApp = /proj/mycoolexecutable; $myOptions = -f -n2 file1 file2; # execute $myApp. .$myOptions here, and do not wait for any return values See: perldoc -f fork perldoc -f exec Thanks for replying zsdc. The $1,$2 thing makes perfect sense now. As for the fork/exec thing, those pages are a little over my head. I don't understandhow process signals and pipes work. Really, all I want the perl script to do is the equivalent of typing $myApp. .$myOptions at the command line, sending its output to STDOUT. This script readsin all input files passed to it, determines which executable applies to each, andlaunches that executable with that file as a parameter. It may need to launch 5 or 6processes, but I want it to gracefully exit when it's done launching and not wait tillthose processes finish. Does that make sense? Is that even possible? Thanks again. - Bryan -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested pattern match
Rob and David, Thanks very much! That's exactly what I am looking for and sorry for the misleading subject on the email. Rob: Could you please explain why you need 2 questions marks on line#7 instead of just one minimal quantifier needed (I hope I am using the right words this time !!!). Thanks, Ramesh 1 while ( $code =~ m{ 2\#(ifn?def) \s+ def \s* \n 3(.*?) \s+ 4(?: 5\#else \s+ def \s* \n 6(.*?) \s+ 7)?? 8\#endif \s+ def \s* \n 9 }isxg ) { 10 my ($def, $undef) = $1 eq 'ifdef' ? ($2, $3 11 || '') : ($3 || '', $2); 12 printf Defined: %s\n, $def; 13 printf Undefined: %s\n, $undef; 14 print \n; } __ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested pattern match
Raghupathy [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Rob and David, Thanks very much! That's exactly what I am looking for and sorry for the misleading subject on the email. Rob: Could you please explain why you need 2 questions marks on line#7 instead of just one minimal quantifier needed (I hope I am using the right words this time !!!). Thanks, Ramesh 1 while ( $code =~ m{ 2\#(ifn?def) \s+ def \s* \n 3(.*?) \s+ 4(?: 5\#else \s+ def \s* \n 6(.*?) \s+ 7)?? 8\#endif \s+ def \s* \n 9 }isxg ) { 10 my ($def, $undef) = $1 eq 'ifdef' ? ($2, $3 11 || '') : ($3 || '', $2); 12 printf Defined: %s\n, $def; 13 printf Undefined: %s\n, $undef; 14 print \n; } Sure. The first question mark is a quantifier: the same as {0,1}, meaning 'match one repetition if possible, otherwise none'. The second is a non-greedy modifier, turning it into 'match no repetitions if possible, otherwise one'. HTH, Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested pattern match
Raghupathy wrote: Hi All, I have a text file as shown below. How do I match patterns like the following: Pattern to be matched: = #ifndef def .. (anything except #if) #else def ... (anything except #if) #endif def My Input Data: = #ifndef def DELETE sys1..tbl1 #endif def SELECT col1, col2, col3 #ifndef def FROMsys1..tbl1 #else def FROMsys1..tbl2 #endif def WHERE schdid is not null = What I tried is below (but did not work since it captured patterns which had #if nested within the main pattern). $line1 =~ m/#ifndef\s+def(.*?)#else\s+def(.*?)#endif\s+def/isg I thought I knew what you meant, but then I changed my mind! If your input file is, say statement1; #ifdef def1 statement2; #ifdef def2 statement3; #else statement4; #endif statement5; #else statement6; #ifdef def3 statement7; #else statement8; #endif statement9; #endif What is it that you want to capture? Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested pattern match
Rob, The input file you described is not correct, since it has #ifdef def2 statement3; #else statement4; #endif nested within another #ifdef ... #else ... #endif. My input file is the output of diff -D def file1 file2 (on unix). This will generate a file which has the following patterns and none of the patterns can be nested within the other: #ifdef #else ... #endif #ifndef #else ... #endif #ifdef #endif #ifndef #endif I need to substitute the above patterns to be read by a home grown program. I encountered a problem due to the following reason. There was: #ifndef def #endif def- Call it sentence1 #ifndef def ... #else def ... #endif def - Call it sentence2 I tried the following line but it matched sentence1 and sentence2 together. I need to match sentence1 and sentence2 seperately. $line1 =~ m/#ifndef\s+def(.*?)#else\s+def(.*?)#endif\s+def/isg For this #ifndef def (...1...) #else def (...2...) #endif def should be matched only if #if is not there within (...1...) and (...2...). Hopefully I have conveyed it more clearly. Thanks, Raghu == Raghupathy wrote: Hi All, I have a text file as shown below. How do I match patterns like the following: Pattern to be matched: = #ifndef def .. (anything except #if) #else def ... (anything except #if) #endif def My Input Data: = #ifndef def DELETE sys1..tbl1 #endif def SELECT col1, col2, col3 #ifndef def FROMsys1..tbl1 #else def FROMsys1..tbl2 #endif def WHERE schdid is not null = What I tried is below (but did not work since it captured patterns which had #if nested within the main pattern). $line1 =~ m/#ifndef\s+def(.*?)#else\s+def(.*?)#endif\s+def/isg I thought I knew what you meant, but then I changed my mind! If your input file is, say statement1; #ifdef def1 statement2; #ifdef def2 statement3; #else statement4; #endif statement5; #else statement6; #ifdef def3 statement7; #else statement8; #endif statement9; #endif What is it that you want to capture? Rob __ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: nested pattern match
Raghupathy wrote: Rob, The input file you described is not correct, since it has #ifdef def2 statement3; #else statement4; #endif nested within another #ifdef ... #else ... #endif. My input file is the output of diff -D def file1 file2 (on unix). This will generate a file which has the following patterns and none of the patterns can be nested within the other: #ifdef #else ... #endif #ifndef #else ... #endif #ifdef #endif #ifndef #endif I need to substitute the above patterns to be read by a home grown program. I encountered a problem due to the following reason. There was: #ifndef def #endif def- Call it sentence1 #ifndef def ... #else def ... #endif def - Call it sentence2 I tried the following line but it matched sentence1 and sentence2 together. I need to match sentence1 and sentence2 seperately. $line1 =~ m/#ifndef\s+def(.*?)#else\s+def(.*?)#endif\s+def/isg For this #ifndef def (...1...) #else def (...2...) #endif def should be matched only if #if is not there within (...1...) and (...2...). Hopefully I have conveyed it more clearly. still not quit sure what you need but try the following: #!/usr/bin/perl -w use strict; my $code =C; #ifdef debug debug defined! #endif debug #ifndef fork no fork no pfork #else fork great os #endif fork C while($code =~ / \#if n? def \s+ ([^\n]+) (.*?) (?: \#else \s+ \1 (.*?) )? \#endif \s+ \1 /gsx){ my $if = $2; my $else = $3 || ''; print $1:,$if; print $1 else: ,$else if($else); } __END__ prints: debug: debug defined! fork: no fork no pfork fork else: great os not sure if that's what you want. david -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
RE: Nested hash creation help !
Thanks Jose! I have the hash created and now can see the values using Data::Dumper but now I an having trouble walking the hashtree. Trying to walk back out to each leaf value in the tree. Hash def $time={$custname}{$custsub}{$site}{$YYMMDDay}{'start'} = $hhmmsss; This doesn't seem to get anything but $c. foreach my $c (sort keys %time) { print Cust $c\n; foreach my $cs (sort keys %{$time-{$c}}) { foreach my $s (sort keys %{$time-{$c}-{$cs}}) { print Site $c.$cs.$s \n #..etc . next branch . etc } } } -Original Message- From: NYIMI Jose (BMB) [mailto:[EMAIL PROTECTED]] Sent: Monday, January 20, 2003 6:11 AM To: [EMAIL PROTECTED]; Beginners Perl Subject: RE: Nested hash creation help ! Afterwards, to see how your nested hash looks like, try this: use Data::Dumper; print Dumper(\%time); José. -Original Message- From: Scot Needy [mailto:[EMAIL PROTECTED]] Sent: Monday, January 20, 2003 6:50 AM To: Beginners Perl Subject: Nested hash creation help ! Hi; Trying to crate a nested hash from variables parsed out of log files but as I am a Beginner Perl' coder it is failing terribly. The basic question is given you have 5 variables how would you make a nested hash. Thanks ! Scot I hope this is enough code to example my problem. -- snip -- foreach (@wwwlogs) { %time=(); ($wwwname,$cust,$YYMMDDay) = split('\.',$_); open (LOG, $_ ) || die Can't open $_!: $! \n; while (LOG) { chomp; # Walk through log file and look for our string. ($pid,$hhmmss,$host,$custname,$custsub,$site,$junk) = split('\|',$_); # print(SPLITVARS= $hhmmss,$host,$custname,$custsub,$site\n); $time={$custname}={$custsub}={$site}={$YYMMDDay} = $hhmmss; } etc etc etc -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] DISCLAIMER This e-mail and any attachment thereto may contain information which is confidential and/or protected by intellectual property rights and are intended for the sole use of the recipient(s) named above. Any use of the information contained herein (including, but not limited to, total or partial reproduction, communication or distribution in any form) by other persons than the designated recipient(s) is prohibited. If you have received this e-mail in error, please notify the sender either by telephone or by e-mail and delete the material from any computer. Thank you for your cooperation. For further information about Proximus mobile phone services please see our website at http://www.proximus.be or refer to any Proximus agent. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
RE: Nested hash creation help !
Thanks to Jose and all others who posted. I now have a working nested hash and a better understanding of them. Scot -Original Message- From: NYIMI Jose (BMB) [mailto:[EMAIL PROTECTED]] Sent: Tuesday, January 21, 2003 7:34 AM To: [EMAIL PROTECTED] Subject: RE: Nested hash creation help ! -Original Message- From: Scot Needy [mailto:[EMAIL PROTECTED]] Sent: Monday, January 20, 2003 4:58 PM To: NYIMI Jose (BMB); Beginners Perl Subject: RE: Nested hash creation help ! Thanks Jose! I have the hash created and now can see the values using Data::Dumper but now I an having trouble walking the hashtree. Trying to walk back out to each leaf value in the tree. Hash def $time={$custname}{$custsub}{$site}{$YYMMDDay}{'start'} = $hhmmsss; This doesn't seem to get anything but $c. foreach my $c (sort keys %time) { print Cust $c\n; foreach my $cs (sort keys %{$time-{$c}}) { If you write this $time-{key} that means the variable 'time' is a 'reference to an hash' not an 'hash'. Since you declared your 'time' beeing an hash as follow: %time=(); You should not be using the arrow notation. Use this intead : $time{key} If really want to arrow notation, you need to declare 'time' like this : my $time={};#reference to an anonymous hash #filling-in as follow $time-{$custname}{$custsub}{$site}{$YYMMDDay}{'start'} = $hhmmsss; #dereference stuff foreach my $c (sort keys %{$time} ) { bla bla .. } HTH, José. foreach my $s (sort keys %{$time-{$c}-{$cs}}) { print Site $c.$cs.$s \n #..etc . next branch . etc } } } -Original Message- From: NYIMI Jose (BMB) [mailto:[EMAIL PROTECTED]] Sent: Monday, January 20, 2003 6:11 AM To: [EMAIL PROTECTED]; Beginners Perl Subject: RE: Nested hash creation help ! Afterwards, to see how your nested hash looks like, try this: use Data::Dumper; print Dumper(\%time); José. -Original Message- From: Scot Needy [mailto:[EMAIL PROTECTED]] Sent: Monday, January 20, 2003 6:50 AM To: Beginners Perl Subject: Nested hash creation help ! Hi; Trying to crate a nested hash from variables parsed out of log files but as I am a Beginner Perl' coder it is failing terribly. The basic question is given you have 5 variables how would you make a nested hash. Thanks ! Scot I hope this is enough code to example my problem. -- snip -- foreach (@wwwlogs) { %time=(); ($wwwname,$cust,$YYMMDDay) = split('\.',$_); open (LOG, $_ ) || die Can't open $_!: $! \n; while (LOG) { chomp; # Walk through log file and look for our string. ($pid,$hhmmss,$host,$custname,$custsub,$site,$junk) = split('\|',$_); # print(SPLITVARS= $hhmmss,$host,$custname,$custsub,$site\n); $time={$custname}={$custsub}={$site}={$YYMMDDay} = $hhmmss; } etc etc etc -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] DISCLAIMER This e-mail and any attachment thereto may contain information which is confidential and/or protected by intellectual property rights and are intended for the sole use of the recipient(s) named above. Any use of the information contained herein (including, but not limited to, total or partial reproduction, communication or distribution in any form) by other persons than the designated recipient(s) is prohibited. If you have received this e-mail in error, please notify the sender either by telephone or by e-mail and delete the material from any computer. Thank you for your cooperation. For further information about Proximus mobile phone services please see our website at http://www.proximus.be or refer to any Proximus agent. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
RE: Nested hash creation help !
Having a quick look, I may say your ploblem can be solved with hash references. Something like: my %hash_level1=(); my %hash_level2=(); $hash_level1{'tag'}=\%hash_level2; To retrieve a value form hash_level2: my $hash_p= $hash_level1{'tag'}; Return ${$hash_p}{'tag_from_level2'}; Hope it helps, Duarte -- Duarte Manuel Cordeiro Manager - IT Infraestructure - Security Communications mailto:[EMAIL PROTECTED] | msn: [EMAIL PROTECTED] | http://www.neoris.com/ -- Neoris Portugal Edificio Inovação IV - Sala 819 - Taguspark * 2780-920 Oeiras * Portugal Tel: +351 21 423-8350 | Fax: +351 21 421-7626 | Mob: +35191 613-5706 -- -Original Message- From: Scot Needy [mailto:[EMAIL PROTECTED]] Sent: Monday, January 20, 2003 5:50 AM To: Beginners Perl Subject: Nested hash creation help ! Hi; Trying to crate a nested hash from variables parsed out of log files but as I am a Beginner Perl' coder it is failing terribly. The basic question is given you have 5 variables how would you make a nested hash. Thanks ! Scot I hope this is enough code to example my problem. -- snip -- foreach (@wwwlogs) { %time=(); ($wwwname,$cust,$YYMMDDay) = split('\.',$_); open (LOG, $_ ) || die Can't open $_!: $! \n; while (LOG) { chomp; # Walk through log file and look for our string. ($pid,$hhmmss,$host,$custname,$custsub,$site,$junk) = split('\|',$_); # print(SPLITVARS= $hhmmss,$host,$custname,$custsub,$site\n); $time={$custname}={$custsub}={$site}={$YYMMDDay} = $hhmmss; } etc etc etc -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Nested hash creation help !
Scot Needy wrote: Hi; Hello, Trying to crate a nested hash from variables parsed out of log files but as I am a Beginner Perl' coder it is failing terribly. The basic question is given you have 5 variables how would you make a nested hash. I hope this is enough code to example my problem. -- snip -- foreach (@wwwlogs) { %time=(); ($wwwname,$cust,$YYMMDDay) = split('\.',$_); The first argument to split is a regular expression. my ( $wwwname, $cust, $YYMMDDay ) = split /\./; open (LOG, $_ ) || die Can't open $_!: $! \n; while (LOG) { chomp; # Walk through log file and look for our string. ($pid,$hhmmss,$host,$custname,$custsub,$site,$junk) = split('\|',$_); my ( $pid, $hhmmss, $host, $custname, $custsub, $site ) = split /\|/; # print(SPLITVARS= $hhmmss,$host,$custname,$custsub,$site\n); $time={$custname}={$custsub}={$site}={$YYMMDDay} = $hhmmss; You are using the = operator which is the same as a comma when you should be using the - operator to dereference hash references. $time{$custname}-{$custsub}-{$site}-{$YYMMDDay} = $hhmmss; Which could also be written as: $time{$custname}{$custsub}{$site}{$YYMMDDay} = $hhmmss; } etc etc etc You can simplify things if you store the log file names in @ARGV instead of @wwwlogs. @ARGV = @wwwlogs; my %time; while ( ) { my ( $wwwname, $cust, $YYMMDDay ) = split /\./, $ARGV if $. == 1; chomp; # Walk through log file and look for our string. my ( $pid, $hhmmss, $host, $custname, $custsub, $site ) = split /\|/; # print(SPLITVARS= $hhmmss,$host,$custname,$custsub,$site\n); $time{$custname}{$custsub}{$site}{$YYMMDDay} = $hhmmss; # etc etc etc if ( eof ) { close ARGV; %time = (); } } __END__ John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
RE: Nested hash creation help !
I would be writing this: #!/usr/bin/perl -w use strict; foreach my $logfile (@wwwlogs) { my %time=(); my ($wwwname,$cust,$YYMMDDay) = split(/\./,$logfile); open (LOG, $logfile) || die Can't open $logfile : $! \n; while (LOG) { chomp; # Walk through log file and look for our string. my($pid,$hhmmss,$host,$custname,$custsub,$site,$junk) = split /\|/; # print(SPLITVARS= $hhmmss,$host,$custname,$custsub,$site\n); $time{$custname}{$custsub}{$site}{$YYMMDDay}=$hhmmss; } close(LOG); etc etc ... } Not tested ! HTH, José. -Original Message- From: Scot Needy [mailto:[EMAIL PROTECTED]] Sent: Monday, January 20, 2003 6:50 AM To: Beginners Perl Subject: Nested hash creation help ! Hi; Trying to crate a nested hash from variables parsed out of log files but as I am a Beginner Perl' coder it is failing terribly. The basic question is given you have 5 variables how would you make a nested hash. Thanks ! Scot I hope this is enough code to example my problem. -- snip -- foreach (@wwwlogs) { %time=(); ($wwwname,$cust,$YYMMDDay) = split('\.',$_); open (LOG, $_ ) || die Can't open $_!: $! \n; while (LOG) { chomp; # Walk through log file and look for our string. ($pid,$hhmmss,$host,$custname,$custsub,$site,$junk) = split('\|',$_); # print(SPLITVARS= $hhmmss,$host,$custname,$custsub,$site\n); $time={$custname}={$custsub}={$site}={$YYMMDDay} = $hhmmss; } etc etc etc -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] DISCLAIMER This e-mail and any attachment thereto may contain information which is confidential and/or protected by intellectual property rights and are intended for the sole use of the recipient(s) named above. Any use of the information contained herein (including, but not limited to, total or partial reproduction, communication or distribution in any form) by other persons than the designated recipient(s) is prohibited. If you have received this e-mail in error, please notify the sender either by telephone or by e-mail and delete the material from any computer. Thank you for your cooperation. For further information about Proximus mobile phone services please see our website at http://www.proximus.be or refer to any Proximus agent. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
RE: Nested hash creation help !
Afterwards, to see how your nested hash looks like, try this: use Data::Dumper; print Dumper(\%time); José. -Original Message- From: Scot Needy [mailto:[EMAIL PROTECTED]] Sent: Monday, January 20, 2003 6:50 AM To: Beginners Perl Subject: Nested hash creation help ! Hi; Trying to crate a nested hash from variables parsed out of log files but as I am a Beginner Perl' coder it is failing terribly. The basic question is given you have 5 variables how would you make a nested hash. Thanks ! Scot I hope this is enough code to example my problem. -- snip -- foreach (@wwwlogs) { %time=(); ($wwwname,$cust,$YYMMDDay) = split('\.',$_); open (LOG, $_ ) || die Can't open $_!: $! \n; while (LOG) { chomp; # Walk through log file and look for our string. ($pid,$hhmmss,$host,$custname,$custsub,$site,$junk) = split('\|',$_); # print(SPLITVARS= $hhmmss,$host,$custname,$custsub,$site\n); $time={$custname}={$custsub}={$site}={$YYMMDDay} = $hhmmss; } etc etc etc -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] DISCLAIMER This e-mail and any attachment thereto may contain information which is confidential and/or protected by intellectual property rights and are intended for the sole use of the recipient(s) named above. Any use of the information contained herein (including, but not limited to, total or partial reproduction, communication or distribution in any form) by other persons than the designated recipient(s) is prohibited. If you have received this e-mail in error, please notify the sender either by telephone or by e-mail and delete the material from any computer. Thank you for your cooperation. For further information about Proximus mobile phone services please see our website at http://www.proximus.be or refer to any Proximus agent. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Nested hash creation help !
John W. Krahn wrote: Scot Needy wrote: Hi; Hello, Trying to crate a nested hash from variables parsed out of log files but as I am a Beginner Perl' coder it is failing terribly. The basic question is given you have 5 variables how would you make a nested hash. I hope this is enough code to example my problem. -- snip -- foreach (@wwwlogs) { %time=(); ($wwwname,$cust,$YYMMDDay) = split('\.',$_); The first argument to split is a regular expression. my ( $wwwname, $cust, $YYMMDDay ) = split /\./; But, as it has an implied 'm', any delimiter will do. The original is fine :) Cheers, Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Nested hash creation help !
Scot Needy wrote: Hi; Trying to crate a nested hash from variables parsed out of log files but as I am a Beginner Perl' coder it is failing terribly. The basic question is given you have 5 variables how would you make a nested hash. Thanks ! Scot I hope this is enough code to example my problem. -- snip -- foreach (@wwwlogs) { %time=(); ($wwwname,$cust,$YYMMDDay) = split('\.',$_); open (LOG, $_ ) || die Can't open $_!: $! \n; while (LOG) { chomp; # Walk through log file and look for our string. ($pid,$hhmmss,$host,$custname,$custsub,$site,$junk) = split('\|',$_); # print(SPLITVARS= $hhmmss,$host,$custname,$custsub,$site\n); $time={$custname}={$custsub}={$site}={$YYMMDDay} = $hhmmss; } etc etc etc People have offered you some fine corrections to your code, but I wonder if this is what you really want? The hash is very deeply nested and is only necessary if you need to access you data this way. Also I think you may well have multiple times per date to store, so that subsequent times from the log file will simply overwrite what you have already. Perhaps this is of some help: my $custsite = $custname|$custsub|$site; my $time= $YYMMDDay:$hhmmss; $time{$custsite}[$i++], $time; ( equivalent to 'push @{$time{$custsite}}, $time' ) i.e. an array of date/times for each customer site. Don't copy this code verbatim, I'm trying to describe a data structure rather than write functional code. Cheers, Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]