Output:use strict; print scalar <DATA>; # print first #PLOT1 while (<DATA>) { chomp; # get rid of EOL print /#PLOT/ ? "\n$_\n" : "$_ "; } ## end while (<DATA>) __DATA__ #PLOT1 a b c d f g i a c g s h b h f d #PLOT2 b g d i s e w d u b a o n i o p w q c u s t r r y #PLOT3 e r t d v g v g b
If you don't know the number of iterations beforehand, use while, otherwise a for loop is more elegant.#PLOT1 a b c d f g i a c g s h b h f d #PLOT2 b g d i s e w d u b a o n i o p w q c u s t r r y #PLOT3 e r t d v g v g b
Whether it is better (for whatever definition of better) I do not know. My solution uses very little memory as it never holds more than one line in memory, whereas a foreach based solution will (usually) hold all the data in memory at once. Of course for such a small sample of data it does not matter.
CountZero
A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James
In reply to Re: while or for?
by CountZero
in thread while or for?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |