Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: loop array excluding some elements

by AnomalousMonk (Chancellor)
on Mar 08, 2018 at 17:58 UTC ( #1210523=note: print w/replies, xml ) Need Help??


in reply to loop array excluding some elements

I like this sort of pattern (update: maybe "style" would be a better word to use here than "pattern"):

c:\@Work\Perl\monks>perl -wMstrict -le "my @SlectedColumns = (9, 7, 6, 0, 5, 0, 4, 3, 2, 0, 1, 9, 9); my $end_index = 10; ;; COLUMN: for my $col (@SlectedColumns[1 .. $end_index]) { next COLUMN unless $col != 0; print qq{do something with col $col}; } " do something with col 7 do something with col 6 do something with col 5 do something with col 4 do something with col 3 do something with col 2 do something with col 1
An  if (COND) { ... } structure with its messy indentation and visual presentation is avoided, and cyclomatic complexity is reduced.

Update 1: In my experience, this pattern turns up quite often in a context like:

use constant RX_COMMENT => qr{ ... }xms; ... ... sub is_valid { my ($string, ) = @_; return $string =~ RX_COMMENT ? 0 : $string =~ RX_BLANK_STRING ? 0 : $string =~ RX_VALID_LINE ? 1 : die "invalid: '$string'" # default ; } ... ... LINE: while (my $line = <$fh>) { next LINE unless is_valid($line); do_something_with_known_valid($line); do_something_else_with($line); ... } # end while LINE

Update 2: This is my 4000th writeup!


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: loop array excluding some elements
by Laurent_R (Canon) on Mar 09, 2018 at 07:29 UTC
    This is my 4000th writeup!
    Congratulations. :)
Re^2: loop array excluding some elements
by Happy-the-monk (Canon) on Mar 09, 2018 at 08:06 UTC

    This is my 4000th writeup!

    I'm glad to have read many of them.

    Cheers, Sören

    Créateur des bugs mobiles - let loose once, run everywhere.
    (hooked on the Perl Programming language)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1210523]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2018-07-22 18:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















    Results (455 votes). Check out past polls.

    Notices?