in reply to Different result for 'foreach' vs 'while shift' arrayref
Hi :)
Hmm, I've never done that :) when I see those statements i think: I'd write while array not empty ... modify array so
while( @letters > 2 ){ while( @dirs ){ while( @files ){ while( @ARGV ){ while( @nodes ){ ...
I thought, hey, maybe in list context..
$ perl -MData::Dump -e " my @f = ( 1, 0, undef, 6 ); while( my($q)=sh +ift @f ){ dd( $q ); $r++; die if $r > 10; } " 1 0 undef 6 undef undef undef undef undef undef undef Died at -e line 1.
But as you can see infinite loop is infinite :) same as $ perl -e " my @f = ( 1, 0, undef, 6 ); while( my@q=shift @f ){ dd( @q ); $r++; die if $r > 10; } "
because shift returns undef to signal no more elements, even in scalar context
I remember a recent discussion about that shift in list context buggy?
So, very nice thread/question gvandeweyer, makes made me examine why I write code the way I write ... its amazing how much stuff just slips into your mind while you're unaware ... I believe I learned to write while(@array) from good code examples ... after its the way I think :)
Hmm, I'm getting another idea, if you didn't notice your array values can be undef while testing/developing, a supplemental warning could be useful; should be easy to write since Perl::Critic::Policy is xpaths , and naming is always the hard part
Perl::Critic::Policy::BuiltinFunctions::ProhibitWhileShift - don't write while($foo=shift@bar) instead write while(@bar)
Perl::Critic::Policy::ControlStructures::ProhibitWhileShiftArray - don't write while($foo=shift@bar) instead write while(@bar)
Perl::Critic::Policy::Variables::ProhibitWhileLoopShiftArray - don't write while($foo=shift@bar) instead write while(@bar)
Perl::Critic::Policy::ControlStructures::LoopTestConditionArray - don't write while($foo=shift@bar) instead write while(@bar)
Thanks again gvandeweyer
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Different result for 'foreach' vs 'while shift' arrayref (Perl::Critic::Policy::ControlStructures::ProhibitShiftLoopCondition)
by Anonymous Monk on Apr 19, 2014 at 06:28 UTC |