Re: capture error - the better way?
On Tuesday 15 Dec 2009 09:50:27 Xiao Lan (小兰) wrote: Hello, It seems in ruby and python we have a good exception capturing way. The ruby's: irb(main):042:0 begin irb(main):043:1* x=12/0 irb(main):044:1 rescue irb(main):045:1 puts 0 div error irb(main):046:1 end 0 div error The python's: try: ... x=12/0 ... except: ... print 0 div error ... 0 div error But in Perl I have to use an eval: # perl -e ' eval $x=12/0; if ($@) { print 0 div error }' 0 div error So what's the equivalent of perl's exception handling like python/ruby? You can use block eval {} instead of string eval : #!/usr/bin/perl use strict; use warnings; my $x; eval { $x=12/0; }; if ($@) { print 0 div error\n; } One problem with that is that Perl 5's exception handling is not inherently object-oriented. If you'd like that (and you likely would), look at the following CPAN modules: * http://search.cpan.org/dist/Exception-Class/ * http://search.cpan.org/dist/TryCatch/ (never used it though). * http://search.cpan.org/dist/Try-Tiny/ (likewise). There's also http://search.cpan.org/dist/Error/ , which I've used, and have been co-maintaining, but cannot really recommend because it is Black Magick and quirky. Regards, Shlomi Fish Thanks in advance. -- - Shlomi Fish http://www.shlomifish.org/ Stop Using MSIE - http://www.shlomifish.org/no-ie/ Bzr is slower than Subversion in combination with Sourceforge. ( By: http://dazjorz.com/ ) -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: capture error - the better way?
On Tue, Dec 15, 2009 at 6:34 PM, Shlomi Fish shlo...@iglu.org.il wrote: You can use block eval {} instead of string eval : #!/usr/bin/perl use strict; use warnings; my $x; eval { $x=12/0; }; if ($@) { print 0 div error\n; } I did have tried that, but this will get a runtime error. # perl -e ' eval { $x = 12/0 }; if ($@) { print 0 div error }' Illegal division by zero at -e line 2. My perl version: # perl -v This is perl, v5.8.8 built for i486-linux-thread-multi One problem with that is that Perl 5's exception handling is not inherently object-oriented. If you'd like that (and you likely would), look at the following CPAN modules: * http://search.cpan.org/dist/Exception-Class/ * http://search.cpan.org/dist/TryCatch/ (never used it though). * http://search.cpan.org/dist/Try-Tiny/ (likewise). Thanks Shlomi, I will check out them. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: capture error - the better way?
2009/12/15 Xiao Lan (小兰) practicalp...@gmail.com: On Tue, Dec 15, 2009 at 6:34 PM, Shlomi Fish shlo...@iglu.org.il wrote: You can use block eval {} instead of string eval : I did have tried that, but this will get a runtime error. # perl -e ' eval { $x = 12/0 }; if ($@) { print 0 div error }' Illegal division by zero at -e line 2. [OT: Are you running this as root? You should avoid being root whenever you can.] That's odd. It works on my machine: $ perl -le ' eval { $x = 12/0 }; if ($@) { print 0 div error }' 0 div error $ perl -v This is perl, v5.10.0 built for x86_64-linux-gnu-thread-multi I can only guess that perl5.8.8 is not catching exceptions in constants caused by evaluating compile time constants. String eval delays evaluation to runtime which would stop this bug manifesting; but this feature is exactly the reason why string eval is /bad/. Does this work for you? $ perl -le 'eval { die died; }; if ($@) { print Caught exception; }' I would expect this to print Caught exception and not died, which indeed is what happens on my machine. Phil -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: capture error - the better way?
On Tue, Dec 15, 2009 at 7:50 PM, Xiao Lan (小兰) practicalp...@gmail.com wrote: I did have tried that, but this will get a runtime error. Sorry this is exactly a compile-time error. # cat except.pl eval { $x=12/0 }; print 0 div error if $@; # perl -c except.pl Illegal division by zero at except.pl line 2. So, can't we capture it at runtime when meeting such error? -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: capture error - the better way?
On Tuesday 15 Dec 2009 14:25:28 Xiao Lan (小兰) wrote: On Tue, Dec 15, 2009 at 7:50 PM, Xiao Lan (小兰) practicalp...@gmail.com wrote: I did have tried that, but this will get a runtime error. Sorry this is exactly a compile-time error. # cat except.pl eval { $x=12/0 }; print 0 div error if $@; # perl -c except.pl Illegal division by zero at except.pl line 2. So, can't we capture it at runtime when meeting such error? No, you cannot capture compile-time errors at runtime. You'll need to make sure your code compiles before you run it. Note that you can capture such errors if you do perldoc -f require, perldoc -f do (for a filename), string eval , etc. at run-time, in which case perl 5 invokes its compiler to compile some code at run-time. But for run-time exceptions block eval { ... } should work just as well. Regards, Shlomi Fish -- - Shlomi Fish http://www.shlomifish.org/ Star Trek: We, the Living Dead - http://shlom.in/st-wtld Bzr is slower than Subversion in combination with Sourceforge. ( By: http://dazjorz.com/ ) -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: capture error - the better way?
2009/12/15 Shlomi Fish shlo...@iglu.org.il: On Tuesday 15 Dec 2009 14:25:28 Xiao Lan (小兰) wrote: On Tue, Dec 15, 2009 at 7:50 PM, Xiao Lan (小兰) practicalp...@gmail.com wrote: I did have tried that, but this will get a runtime error. Sorry this is exactly a compile-time error. # cat except.pl eval { $x=12/0 }; print 0 div error if $@; # perl -c except.pl Illegal division by zero at except.pl line 2. So, can't we capture it at runtime when meeting such error? No, you cannot capture compile-time errors at runtime. You'll need to make sure your code compiles before you run it. Note that you can capture such errors if you do perldoc -f require, perldoc -f do (for a filename), string eval , etc. at run-time, in which case perl 5 invokes its compiler to compile some code at run-time. How can Illegal division by zero be a compile-time error? It seems clear to me that it's a run-time error, which the optimizer has (wrongly) decided to raise at compile-time. Phil -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: capture error - the better way?
On Tuesday 15 Dec 2009 15:53:28 Philip Potter wrote: 2009/12/15 Shlomi Fish shlo...@iglu.org.il: On Tuesday 15 Dec 2009 14:25:28 Xiao Lan (小兰) wrote: On Tue, Dec 15, 2009 at 7:50 PM, Xiao Lan (小兰) practicalp...@gmail.com wrote: I did have tried that, but this will get a runtime error. Sorry this is exactly a compile-time error. # cat except.pl eval { $x=12/0 }; print 0 div error if $@; # perl -c except.pl Illegal division by zero at except.pl line 2. So, can't we capture it at runtime when meeting such error? No, you cannot capture compile-time errors at runtime. You'll need to make sure your code compiles before you run it. Note that you can capture such errors if you do perldoc -f require, perldoc -f do (for a filename), string eval , etc. at run-time, in which case perl 5 invokes its compiler to compile some code at run-time. How can Illegal division by zero be a compile-time error? It seems clear to me that it's a run-time error, which the optimizer has (wrongly) decided to raise at compile-time. Well, the Perl compiler tends to collapse constants. So if it sees something like: ... ( CONSTANT_EXPR() / 0 ) ... it will try to find the value of CONSTANT_EXPR() / 0 so it can optimise it as a constant for the interpreter, and then get a fault there. It's a standard optimisation technique that also exists in other compilers such as gcc that are collapsing such constant expressions. So it does get evaluated at compile- time and as such should be avoided. Regards, Shlomi Fish Phil -- - Shlomi Fish http://www.shlomifish.org/ The Case for File Swapping - http://shlom.in/file-swap Bzr is slower than Subversion in combination with Sourceforge. ( By: http://dazjorz.com/ ) -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Child process not updating the logs
Hi All, I ran in to a problem. My program was working very fine till last week. When i checked it today, i found that the child process in not updating the log files. I have a daemon process in which a common log file is opened in the parent process, and after forking a child parent will exit. I have the child process capturing all the execution details and store it in to the log file. But from today onwards updating the logs is stopped. When i run it as an individual code, child is updating the files. Anybody got any clue ?. Shammi -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Child process not updating the logs
Shameem Ahamed wrote: Hi All, I ran in to a problem. My program was working very fine till last week. When i checked it today, i found that the child process in not updating the log files. I have a daemon process in which a common log file is opened in the parent process, and after forking a child parent will exit. I have the child process capturing all the execution details and store it in to the log file. But from today onwards updating the logs is stopped. When i run it as an individual code, child is updating the files. Anybody got any clue ?. Not without code. Steve -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: capture error - the better way?
2009/12/15 Shlomi Fish shlo...@iglu.org.il: On Tuesday 15 Dec 2009 15:53:28 Philip Potter wrote: How can Illegal division by zero be a compile-time error? It seems clear to me that it's a run-time error, which the optimizer has (wrongly) decided to raise at compile-time. Well, the Perl compiler tends to collapse constants. So if it sees something like: ... ( CONSTANT_EXPR() / 0 ) ... it will try to find the value of CONSTANT_EXPR() / 0 so it can optimise it as a constant for the interpreter, and then get a fault there. It's a standard optimisation technique that also exists in other compilers such as gcc that are collapsing such constant expressions. So it does get evaluated at compile- time and as such should be avoided. I'm well aware of constant folding, and yes it is a standard technique. But your description of it is incorrect. If evaluating a constant expression results in a runtime exception, that runtime exception must happen at runtime, and not at compile time. In general, it is the duty of an optimizer never to change program behaviour, only performance. Therefore an optimizer which tries to fold a constant expression at compile time only to find a divide by zero exception should write code which raises a divide by zero exception at runtime. Raising a divide by zero exception at compile time is not what the original program did, and so it's not what the optimizer should do either. If an optimizer *were* allowed to move runtime errors to compile time, it wouldn't just prevent use of 1/0. The following reasonable (if unrealistic) example would not be guaranteed to compile: # Check if a division will emit any sort of exception (divide by zero, overflow, underflow, NaN, whatever) sub check_division { my ($n, $d) = @_; eval { $n/$d}; return Invalid division if $@; return Valid division; } # and elsewhere... check_division(1,0); Why? Because if a sufficiently clever optimizer saw that somewhere in your code you call check_division(1,0), it could decide to inline the function there. And once it's done that, it can propagate the constants 1 and 0 into the local versions of the variables $n and $d, producing the constant expression 1/0 within the eval block. Now it merrily decides to calculate this expression's value at compile time, only to emit a compile-time error. If this error had happened at runtime, the program would have caught it and functioned entirely correctly; but by moving the exception to compile time -- and out of the eval block which was supposed to catch any exceptions -- the program won't even compile. If I am supposed to defend against such an overzealous optimizer, how would I write code that uses any block eval to catch exceptions? A sufficiently advanced optimizer could always use some method like that described above to precalculate the results of the eval, triggering an exception at compile time instead of runtime. Therefore block eval could never be guaranteed to catch runtime exceptions! Philip -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
RE: SMTP black hole script
From: Bob McConnell Just to avoid re-inventing a pair of wheels, does anyone have a script that will accept any and all SMTP connections and messages, but dumps them into a file instead of trying to forward them? To close the loop on this question, even though I didn't receive any responses, I found several honey pot packages with SMTP black hole servers in them. I am reviewing a few of them to see which would be the best starting point for my requirements. Thanks, Bob McConnell -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Comparing aggregates for equality when order doesn't matter
Hi all, I have a method which returns two arrayrefs: one is an array of hashes, and the other an array of arrays. I'm writing a test harness for this method, so I put together some testcases and expected results. I don't care what order the arrays are in; I only care that the arrayrefs returned by the function contains exactly the same set of values as the expected results. Something like this: # embeddings is an array of hashes, $anchors is an array of arrays my ($embeddings, $anchors) = $embedder-embed($subgraph); my $expected = { embeddings = [ { a = '1', b = '2', }, { a = '1', b = '3', }, { a = '2', b = '3', }, ], anchors = [ ['1','2'], ['2','3'], ['1','3'], ], }, use Test::More tests = 2; is_deeply($embeddings, $expected-{embeddings}, embeddings match); is_deeply($anchors,$expected-{anchors}, anchors match); ...except that I don't care if the actual and expected array referents are in a different order, only that they contain the same items. My first thought is to sort the arrays according to some arbitrary convention and use is_deeply() as above; but I'm stuck as to how to write a sort ordering well. I'm thinking I should sort the array of hashes by lexicographical ordering of hash values, with lexicographical significance determined by sorted key order, and sort the array of arrays by simple lexicographical order. I have something like this: use List::MoreUtils qw(pairwise); # lexicographical comparison function for lists of hashes sub lexhash { my @seq_a = map {$a-{$_}} sort keys %$a; my @seq_b = map {$b-{$_}} sort keys %$b; for my $pair (pairwise {[$a,$b]} @seq_a, @seq_b) { return $pair-[0] cmp $pair-[1] if $pair-[0] cmp $pair-[1]; } return 0; } # lexicographical comparison function for lists of arrays sub lexarray { for my $pair (pairwise {[$a,$b]} @$a, @$b) { return $pair-[0] cmp $pair-[1] if $pair-[0] cmp $pair-[1]; } return 0; } is_deeply([sort lexhash @$embeddings], [sort lexhash @{$expected-{embeddings}}], embeddings match); is_deeply([sort lexarray @$anchors], [sort lexarray @{$expected-{anchors}}], anchors match); This works and does what I want, but it feels hacky and I'm not entirely happy about it. I have these questions: 1. Is there a set type which holds aggregate data and doesn't care about order, which I could use to compare these results for equality? 2. If not, is my solution to the problem a reasonable design? If not, what better way could I do it? 3. If it's a reasonable design, is there any way my implementation of it could be improved? In particular, could it be made more readable? I'm not convinced that I could work out what this code does next week, let alone in six months time. Phil -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Comparing aggregates for equality when order doesn't matter
Philip Potter wrote: 1. Is there a set type which holds aggregate data and doesn't care about order, which I could use to compare these results for equality? You can use a hash as a set or a bag. #!/usr/bin/perl use strict; use warnings; use Data::Dumper; # Make Data::Dumper pretty $Data::Dumper::Sortkeys = 1; $Data::Dumper::Indent = 1; # Set maximum depth for Data::Dumper, zero means unlimited $Data::Dumper::Maxdepth = 0; my @a = qw( a b c x y z a b ); my %set = map { $_ = 1 } @a; print '%set : ', Dumper \%set; my %bag = (); $bag{$_} ++ for @a; print '%bag : ', Dumper \%bag; __END__ -- Just my 0.0002 million dollars worth, Shawn Programming is as much about organization and communication as it is about coding. I like Perl; it's the only language where you can bless your thingy. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Comparing aggregates for equality when order doesn't matter
2009/12/15 Shawn H Corey shawnhco...@gmail.com: Philip Potter wrote: 1. Is there a set type which holds aggregate data and doesn't care about order, which I could use to compare these results for equality? You can use a hash as a set or a bag. Yeah I thought about this -- while I can see how it works with simple scalars, I can't see how to make it work with references: $ cat foo.pl #!/usr/bin/perl use strict; use warnings; use Data::Dumper; # Make Data::Dumper pretty $Data::Dumper::Sortkeys = 1; $Data::Dumper::Indent = 1; # Set maximum depth for Data::Dumper, zero means unlimited $Data::Dumper::Maxdepth = 0; my @a = ([1],[2],[3]); my @b = ([1],[2],[3]); my %set_a = map { $_ = 1 } @a; print '%set_a : ', Dumper \%set_a; my %set_b = map { $_ = 1 } @b; print '%set_b : ', Dumper \%set_b; use Test::More tests = 1; is_deeply(\%set_a, \%set_b, 'Test that references as hash keys works'); __END__ $ perl foo.pl 1..1 %set_a : $VAR1 = { 'ARRAY(0x1b66c40)' = 1, 'ARRAY(0x1b66df0)' = 1, 'ARRAY(0x1d50550)' = 1 }; %set_b : $VAR1 = { 'ARRAY(0x1ba7010)' = 1, 'ARRAY(0x1d1b3a8)' = 1, 'ARRAY(0x1d84698)' = 1 }; not ok 1 - Test that references as hash keys works # Failed test 'Test that references as hash keys works' # at foo.pl line 26. # Structures begin differing at: # $got-{ARRAY(0x1d1b3a8)} = Does not exist # $expected-{ARRAY(0x1d1b3a8)} = '1' # Looks like you failed 1 test of 1. Perhaps a way of collapsing references to unique strings would work? ie: my %set_a = map { stringify($_) = 1 } @a; where stringify() is a function which maps references to unique strings identifying their referent? Phil -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Modifying files with PERL
I need to add new lines of text with special characters, to specific lines in the file. There are 3 modifications needed. Been testing 2 here without success. #!/usr/bin/perl use FileHandle; $file=FileHandle-new; $FILENAME=/opt/etc/usr/file.txt; $file-open ($FILENAME) or die (Error: $!\n); while ($file) { $count++; if ($count=39) { print qq[RM=rm2];} if ($count=47) { print qq[$RM] } exit; -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Modifying files with PERL
On Tue, Dec 15, 2009 at 10:42 AM, A4r0N mccray...@gmail.com wrote: I need to add new lines of text with special characters, to specific lines in the file. There are 3 modifications needed. Been testing 2 here without success. What error are you getting? What modifications are needed? I know what this script does, but I don't know what it is supposed to do...james -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Modifying files with PERL
On 12/15/09 Tue Dec 15, 2009 7:42 AM, A4r0N mccray...@gmail.com scribbled: I need to add new lines of text with special characters, to specific lines in the file. There are 3 modifications needed. Been testing 2 here without success. #!/usr/bin/perl use FileHandle; $file=FileHandle-new; $FILENAME=/opt/etc/usr/file.txt; $file-open ($FILENAME) or die (Error: $!\n); while ($file) { $count++; if ($count=39) { That should be: if($count==39) { print qq[RM=rm2];} You probably want a newline at the end: print qq[RM=rm2\n]; if ($count=47) { print qq[$RM] Ditto for the above two lines. } exit; -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Modifying files with PERL
A == A4r0N mccray...@gmail.com writes: A I need to add new lines of text with special characters, to specific A lines in the file. There are 3 modifications needed. Been testing 2 A here without success. A #!/usr/bin/perl A use FileHandle; that module is unneeded for such simple use. and FileHandle is obsolete anyhow. just open the file with a normal or lexical handle. see perldoc -f open A $file=FileHandle-new; A $FILENAME=/opt/etc/usr/file.txt; put some whitespace in your code to make it more readable A $file-open ($FILENAME) or die (Error: $!\n); good, you checked the return of open and printed $! A while ($file) { A $count++; A if ($count=39) { as someone else pointed out, that should be ==. but look at $. in perldoc perlvar for a simpler way to do this. A print qq[RM=rm2];} A if ($count=47) { A print qq[$RM] A } as with the above, learn to format your code better. that should all be indented properly to help with reading it. and you never print the line you read from the file itself. that is in $_. 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: Modifying files with PERL
T == Troy magicxiao...@gmail.com writes: T also look at 'perl -i ' . you can modify original file directly please don't email me privately. there is no reason not to post that to the list. i cc'ed the list where my reply belongs. and please don't top post. finally, i am one of the experts on the list so there is no need to tell me about -i. i didn't mention it because it was more then the OP could handle IMO. he had enough problems with his code as it is. explaining to him how to do a -pie loop would take too long. also the work he was doing would be longish for a -pie loop as well, he needed two full statements - checking a line number and then printing a line. i wouldn't recommend that for a one liner. 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/
Perlcritic complains about assignment within conditional
Hi everyone, I'm reviewing a script I wrote that I use against one of my modules. The script takes an optional param at the command line. Although I am seriously reviewing my options for better and smarter ways to utilize command line args, I'm curious as to why perlcritic complains to me, and (in this specific case) how it should have been done differently. Without getting into the different ways to accept and process command line args, will someone point out how _this_ script should have been written to avoid the critic message? Is leaving off the condition the same as having it there? I've left what perlcritic yelled about, and the script in it's entirety. The offending line is marked: acct-dev: ISP-RADIUS % perlcritic src/utilities/aggregate_monthly Variable declared in conditional statement at line 21, column 1. Declare variables outside of the condition. (Severity: 5) #!/usr/bin/perl # - aggregate_monthly # - utility script for ISP::RADIUS # - aggregates totals from aggregate_daily db table into # the aggregate_monthly db table # - same license as module itself # If a month is passed in as the first parameter in the format # -MM, we will operate on that month. Otherwise, the month # that was existent yesterday will be used. use strict; use warnings; use DateTime; use ISP::RADIUS; my $radius = ISP::RADIUS-new(); # issue is down ---vvv my $month = $ARGV[0] if $ARGV[0]; if ( $month !~ m{ \A \d{4}-\d{2} \z }xms ) { print \nInvalid date parameter. Must be supplied as '-MM'\n\n; exit; } if ( $month ) { $radius-aggregate_monthly( { month = $month } ); } else { $radius-aggregate_monthly(); } ~ -- VISUAL -- 331,1 All -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perlcritic complains about assignment within conditional
Steve Bertrand wrote: my $month = $ARGV[0] if $ARGV[0]; $ cat myscript.pl #!/usr/bin/perl use strict; use warnings; my $month = $ARGV[0] if $ARGV[0]; print $month\n; $ ./myscript.pl Use of uninitialized value $month in concatenation (.) or string at ./myscript.pl line 7. Try: my $month = ''; $month = $ARGV[0] if $ARGV[0]; -- Just my 0.0002 million dollars worth, Shawn Programming is as much about organization and communication as it is about coding. I like Perl; it's the only language where you can bless your thingy. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perlcritic complains about assignment within conditional
Shawn H Corey wrote: Steve Bertrand wrote: my $month = $ARGV[0] if $ARGV[0]; $ cat myscript.pl #!/usr/bin/perl use strict; use warnings; my $month = $ARGV[0] if $ARGV[0]; print $month\n; $ ./myscript.pl Use of uninitialized value $month in concatenation (.) or string at ./myscript.pl line 7. Try: my $month = ''; $month = $ARGV[0] if $ARGV[0]; aha! It was the *declaration* part of the critic complaint that I read over. For some reason I was thinking 'assignment'. Perhaps I should read next time. Thanks! Steve ps. again, far better arg handler is in order ;) -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perlcritic complains about assignment within conditional
SHC == Shawn H Corey shawnhco...@gmail.com writes: SHC Steve Bertrand wrote: my $month = $ARGV[0] if $ARGV[0]; that is similar to the broken my $foo = 1 if 0 used to make static vars inside a sub. the assignment won't even happen unless you have a true value. SHC Try: SHC my $month = ''; SHC $month = $ARGV[0] if $ARGV[0]; or just use ||: my $month = $ARGV[0] || '' ; then the assignment always happens and the declaration should be critic clean. you can even just do: my $month = $ARGV[0] ; since you do a boolean test on $month later on. it will handle the same logic you have here. but you do a regex on $month and that would trigger an undef warning if you didn't pass in an arg. so the above code is better. the rule is never use a statement modifier on a declaration. you can almost always get what you want with boolean ops. 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: Perlcritic complains about assignment within conditional
Uri Guttman wrote: SHC == Shawn H Corey shawnhco...@gmail.com writes: SHC Steve Bertrand wrote: my $month = $ARGV[0] if $ARGV[0]; that is similar to the broken my $foo = 1 if 0 used to make static vars inside a sub. the assignment won't even happen unless you have a true value. SHC Try: SHC my $month = ''; SHC $month = $ARGV[0] if $ARGV[0]; or just use ||: my $month = $ARGV[0] || '' ; then the assignment always happens and the declaration should be critic clean. you can even just do: my $month = $ARGV[0] ; since you do a boolean test on $month later on. it will handle the same logic you have here. but you do a regex on $month and that would trigger an undef warning if you didn't pass in an arg. so the above code is better. the rule is never use a statement modifier on a declaration. you can almost always get what you want with boolean ops. Thanks Uri, I was just thinking, but didn't get a chance to test what would happen if I declared $var = '', and then performed a regex check on it. ...without testing yet, I expect ` '' ` to be different than undef, and I would expect my regex check to fail if a variable was declared with a blank string and there is no arg passed in to override the default declaration. I've been going through a lot of my code lately, just to find quicker exit points in subs where code is being executed unnecessarily. The subs that produced warnings tipped me off that I'm executing too much code before jumping out much of the time, so its the ones that don't fire warnings that I've been trying to scrutinize. ...off to see what happens. Steve -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perlcritic complains about assignment within conditional
Uri Guttman wrote: SHC == Shawn H Corey shawnhco...@gmail.com writes: SHC Try: SHC my $month = ''; SHC $month = $ARGV[0] if $ARGV[0]; or just use ||: my $month = $ARGV[0] || '' ; $ cat myscript.pl #!/usr/bin/perl use strict; use warnings; my $month = $ARGV[0] || ''; print month = '$month'\n; $ ./myscript.pl 0 month = '' Doesn't always work right. -- Just my 0.0002 million dollars worth, Shawn Programming is as much about organization and communication as it is about coding. I like Perl; it's the only language where you can bless your thingy. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: capture error - the better way?
Xiao Lan (小兰) wrote: eval $x=12/0; if ($@) { print 0 div error }' 0 div error Don't rely on testing $@, simply because it is a global variable that can get changed everywhere. Instead, test the return value of the eval itself. (Don't forget to let it return 1 for success, just like with modules.) Avoid string-eval whenever possible. perl -wle ' my $y = 0; if ( !eval { 42 / $y; 1 } ) { my $error = $@ || unknown; print $error; } ' Illegal division by zero at -e line 3. -- Ruud -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perlcritic complains about assignment within conditional
Steve Bertrand wrote: Uri Guttman wrote: SHC == Shawn H Corey shawnhco...@gmail.com writes: SHC Steve Bertrand wrote: my $month = $ARGV[0] if $ARGV[0]; that is similar to the broken my $foo = 1 if 0 used to make static vars inside a sub. the assignment won't even happen unless you have a true value. SHC Try: SHC my $month = ''; SHC $month = $ARGV[0] if $ARGV[0]; or just use ||: my $month = $ARGV[0] || '' ; then the assignment always happens and the declaration should be critic clean. you can even just do: my $month = $ARGV[0] ; since you do a boolean test on $month later on. it will handle the same logic you have here. but you do a regex on $month and that would trigger an undef warning if you didn't pass in an arg. so the above code is better. the rule is never use a statement modifier on a declaration. you can almost always get what you want with boolean ops. Thanks Uri, I was just thinking, but didn't get a chance to test what would happen if I declared $var = '', and then performed a regex check on it. This tells me that pre-declaring a var with '' makes my original logic fail: % perl -e '$var=; print 2 if $var !~ /1/; print 1 if $var' ...so in this case, I'd have to switch my logic backwards, and change my original regex check: if ( $month !~ m{ \A \d{4}-\d{2} \z }xms ) to something like this: if ( $month $month !~ m{ \A \d{4}-\d{2} \z }xms ) yes? *also*... how can I use 'perl' on the command line, but in a way that I can use multiple lines in my terminal? I see many code snips for Perl one-liners that cover multiple lines. Is this a copy/paste/cleanup job? eg: % perl -e 'print [ENTER pressed] Unmatched '. ...on FreeBSD. Steve -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perlcritic complains about assignment within conditional
Steve Bertrand wrote: Hi everyone, Hello, I'm reviewing a script I wrote that I use against one of my modules. The script takes an optional param at the command line. Although I am seriously reviewing my options for better and smarter ways to utilize command line args, I'm curious as to why perlcritic complains to me, and (in this specific case) how it should have been done differently. Without getting into the different ways to accept and process command line args, will someone point out how _this_ script should have been written to avoid the critic message? Is leaving off the condition the same as having it there? I've left what perlcritic yelled about, and the script in it's entirety. The offending line is marked: acct-dev: ISP-RADIUS % perlcritic src/utilities/aggregate_monthly Variable declared in conditional statement at line 21, column 1. Declare variables outside of the condition. (Severity: 5) #!/usr/bin/perl # - aggregate_monthly # - utility script for ISP::RADIUS # - aggregates totals from aggregate_daily db table into # the aggregate_monthly db table # - same license as module itself # If a month is passed in as the first parameter in the format # -MM, we will operate on that month. Otherwise, the month # that was existent yesterday will be used. use strict; use warnings; use DateTime; use ISP::RADIUS; my $radius = ISP::RADIUS-new(); # issue is down ---vvv my $month = $ARGV[0] if $ARGV[0]; perldoc perlsyn [ SNIP ] NOTE: The behaviour of a my statement modified with a statement modifier conditional or loop construct (e.g. my $x if ...) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don’t rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons. if ( $month !~ m{ \A \d{4}-\d{2} \z }xms ) { print \nInvalid date parameter. Must be supplied as '-MM'\n\n; exit; You exit the program if $month is not equal to a seven character string. } if ( $month ) { A seven character string is *always* true. $radius-aggregate_monthly( { month = $month } ); } else { So this branch will *never* execute, and the whole test is superfluous. $radius-aggregate_monthly(); } Probably better as: if ( $month =~ /\A\d{4}-\d{2}\z/ ) { $radius-aggregate_monthly( { month = $month } ); } else { print \nInvalid date parameter. Must be supplied as '-MM'\n\n; exit 1; # non-zero exit lets the OS know an error occured } John -- The programmer is fighting against the two most destructive forces in the universe: entropy and human stupidity. -- Damian Conway -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perlcritic complains about assignment within conditional
On 12/15/09 Tue Dec 15, 2009 4:49 PM, Shawn H Corey shawnhco...@gmail.com scribbled: Steve Bertrand wrote: my $month = $ARGV[0] if $ARGV[0]; $ cat myscript.pl #!/usr/bin/perl use strict; use warnings; my $month = $ARGV[0] if $ARGV[0]; print $month\n; $ ./myscript.pl Use of uninitialized value $month in concatenation (.) or string at ./myscript.pl line 7. Try: my $month = ''; $month = $ARGV[0] if $ARGV[0]; Or try: my $month = ( @ARGV ? $ARGV[0] : '' ); which allows you to enter '0' as an argument. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perlcritic complains about assignment within conditional
Steve, You need to declare $month in a separate line. The variable may not exist if the statement evaluate to false. I think that's what it is complaining about. -venkat On 12/15/09, Steve Bertrand st...@ibctech.ca wrote: Hi everyone, I'm reviewing a script I wrote that I use against one of my modules. The script takes an optional param at the command line. Although I am seriously reviewing my options for better and smarter ways to utilize command line args, I'm curious as to why perlcritic complains to me, and (in this specific case) how it should have been done differently. Without getting into the different ways to accept and process command line args, will someone point out how _this_ script should have been written to avoid the critic message? Is leaving off the condition the same as having it there? I've left what perlcritic yelled about, and the script in it's entirety. The offending line is marked: acct-dev: ISP-RADIUS % perlcritic src/utilities/aggregate_monthly Variable declared in conditional statement at line 21, column 1. Declare variables outside of the condition. (Severity: 5) #!/usr/bin/perl # - aggregate_monthly # - utility script for ISP::RADIUS # - aggregates totals from aggregate_daily db table into # the aggregate_monthly db table # - same license as module itself # If a month is passed in as the first parameter in the format # -MM, we will operate on that month. Otherwise, the month # that was existent yesterday will be used. use strict; use warnings; use DateTime; use ISP::RADIUS; my $radius = ISP::RADIUS-new(); # issue is down ---vvv my $month = $ARGV[0] if $ARGV[0]; if ( $month !~ m{ \A \d{4}-\d{2} \z }xms ) { print \nInvalid date parameter. Must be supplied as '-MM'\n\n; exit; } if ( $month ) { $radius-aggregate_monthly( { month = $month } ); } else { $radius-aggregate_monthly(); } ~ -- VISUAL -- 331,1 All -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/ -- Sent from my mobile device with warm regards, Venkat Saranathan Gulf Breeze Software. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perlcritic complains about assignment within conditional
John W. Krahn wrote: Steve Bertrand wrote: Hi everyone, Hello, I'm reviewing a script I wrote that I use against one of my modules. The script takes an optional param at the command line. Although I am seriously reviewing my options for better and smarter ways to utilize command line args, I'm curious as to why perlcritic complains to me, and (in this specific case) how it should have been done differently. Without getting into the different ways to accept and process command line args, will someone point out how _this_ script should have been written to avoid the critic message? Is leaving off the condition the same as having it there? I've left what perlcritic yelled about, and the script in it's entirety. The offending line is marked: acct-dev: ISP-RADIUS % perlcritic src/utilities/aggregate_monthly Variable declared in conditional statement at line 21, column 1. Declare variables outside of the condition. (Severity: 5) #!/usr/bin/perl # - aggregate_monthly # - utility script for ISP::RADIUS # - aggregates totals from aggregate_daily db table into # the aggregate_monthly db table # - same license as module itself # If a month is passed in as the first parameter in the format # -MM, we will operate on that month. Otherwise, the month # that was existent yesterday will be used. use strict; use warnings; use DateTime; use ISP::RADIUS; my $radius = ISP::RADIUS-new(); # issue is down ---vvv my $month = $ARGV[0] if $ARGV[0]; perldoc perlsyn [ SNIP ] NOTE: The behaviour of a my statement modified with a statement modifier conditional or loop construct (e.g. my $x if ...) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don’t rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons. if ( $month !~ m{ \A \d{4}-\d{2} \z }xms ) { print \nInvalid date parameter. Must be supplied as '-MM'\n\n; exit; You exit the program if $month is not equal to a seven character string. ehhh.. *scratching head while thinking about dragons*. Is my regex at least doing what you perceive it should be doing? It tests ok here: % perl -e '$var=-bb; print 1 if $var !~ m{ \A \d{4}-\d{2} \z }xms' I'm so confused :P A seven character string is *always* true. $radius-aggregate_monthly( { month = $month } ); } else { So this branch will *never* execute, and the whole test is superfluous. ...but it works for real against the real database, and I get proper results (with my original code in the OP posting). Probably better as: if ( $month =~ /\A\d{4}-\d{2}\z/ ) { $radius-aggregate_monthly( { month = $month } ); } else { print \nInvalid date parameter. Must be supplied as '-MM'\n\n; exit 1; # non-zero exit lets the OS know an error occured } ...I think I get what you are saying, and I think I found that out in the last message I sent. However, I still don't understand why you claim that my original regex was looking for a seven character string, when I *thought* I was checking for four digits, then two digits separated by a dash (or hyphen, as it were). Thanks John, Steve -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perlcritic complains about assignment within conditional
Steve Bertrand wrote: John W. Krahn wrote: perldoc perlsyn [ SNIP ] NOTE: The behaviour of a my statement modified with a statement modifier conditional or loop construct (e.g. my $x if ...) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don’t rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons. if ( $month !~ m{ \A \d{4}-\d{2} \z }xms ) { print \nInvalid date parameter. Must be supplied as '-MM'\n\n; exit; You exit the program if $month is not equal to a seven character string. Nevermind. I see what you were saying. Technically, I've never tried to get past the regex check with this script (that I can remember)... I completely understand why you said what you did after I reviewed the logic again. Ahh well, I'd rather be vocal and get good feedback to later review than say nothing and never learn! Thanks all, because of a simple `perlcritic` warning, I've learnt a tremendous amount! Steve -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perlcritic complains about assignment within conditional
SB == Steve Bertrand st...@ibctech.ca writes: I was just thinking, but didn't get a chance to test what would happen if I declared $var = '', and then performed a regex check on it. SB This tells me that pre-declaring a var with '' makes my original logic fail: that isn't 'predeclaring' but initializing. SB % perl -e '$var=; print 2 if $var !~ /1/; print 1 if $var' i generally never use !~ but prefer to invert the boolean test. i think it reads better to say unless $var =~ /1/. SB ...so in this case, I'd have to switch my logic backwards, and change my SB original regex check: SB if ( $month !~ m{ \A \d{4}-\d{2} \z }xms ) SB to something like this: SB if ( $month $month !~ m{ \A \d{4}-\d{2} \z }xms ) it depends on how you handle the command line arg. a null string will fail that regex and an arg of '0' will not be checked since the $month test will fail. you said you didn't want any stuff on how you handled command line args i think you do need to address it. it is best to check @ARGV for its size rather than $ARGV[0] for its truth. then you can tell if a null string '' or 0 was passed in. SB *also*... how can I use 'perl' on the command line, but in a way that I SB can use multiple lines in my terminal? I see many code snips for Perl SB one-liners that cover multiple lines. Is this a copy/paste/cleanup job? SB eg: SB % perl -e 'print [ENTER pressed] SB Unmatched '. SB ...on FreeBSD. that is a shell issue, not a perl issue. most shells can handle an open quote with returns inside until you close the quote. bash can do it for sure. 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/
Google/Checkout API
Hello, We are in the process of setting up a checkout page using Paypal and Google's Checkout, using the Google Checkout HTML API. This is simple setup with 3 different single items that can be ordered using Paypal or Google Checkout. Now setting up the Paypal API no problems there. But I haven't worked with the GoogleCheckout HTML API before and have been trying to figure out the best way to set it up. All we need to do is have a checkout button/form to process a single item purchase and receive instant notification that the payment was validated, sucessfull or not, similar to how Paypal works. I've been trying to go through Google docs on their site and the info within the Perl API docs but it's a bit confusing to say the least :) I was hoping someone on the list may have worked with Google's Checkout API with a similar simple setup like this and can steer me in the right direction, creating the payment order form to submit the payment and which API module(s) need to be utilized. There are bunch of different modules/examples scripts used but I'm sure not all of them are needed to process a simple single item order payment and receive the notification. Any help or suggestion would be appreciated. Mike(mickalo)Blezien =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Thunder Rain Internet Publishing http://www.thunder-rain.com/ =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Perlcritic complains about assignment within conditional
Steve Bertrand wrote: John W. Krahn wrote: Steve Bertrand wrote: if ( $month !~ m{ \A \d{4}-\d{2} \z }xms ) { print \nInvalid date parameter. Must be supplied as '-MM'\n\n; exit; You exit the program if $month is not equal to a seven character string. ehhh.. *scratching head while thinking about dragons*. Is my regex at least doing what you perceive it should be doing? It tests ok here: % perl -e '$var=-bb; print 1 if $var !~ m{ \A \d{4}-\d{2} \z }xms' I'm so confused :P A seven character string is *always* true. $radius-aggregate_monthly( { month = $month } ); } else { So this branch will *never* execute, and the whole test is superfluous. ...but it works for real against the real database, and I get proper results (with my original code in the OP posting). Probably better as: if ( $month =~ /\A\d{4}-\d{2}\z/ ) { $radius-aggregate_monthly( { month = $month } ); } else { print \nInvalid date parameter. Must be supplied as '-MM'\n\n; exit 1; # non-zero exit lets the OS know an error occured } ...I think I get what you are saying, and I think I found that out in the last message I sent. However, I still don't understand why you claim that my original regex was looking for a seven character string, The pattern /\A\d{4}-\d{2}\z/ is anchored at the beginning and end and matches exactly four \d characters followed by a '-' character followed by exactly two \d characters hence it will match exactly seven characters. when I *thought* I was checking for four digits, then two digits separated by a dash (or hyphen, as it were). Yes, seven characters, four digit characters, then two digit characters separated by a hyphen character (or dash, as it were.) John -- The programmer is fighting against the two most destructive forces in the universe: entropy and human stupidity. -- Damian Conway -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/