Perl Range operator paradigm
Magnus Lie Hetland
mlh at idi.ntnu.no
Mon Oct 22 11:05:53 EDT 2001
"Martien Verbruggen" <mgjv at tradingpost.com.au> wrote in message
news:slrn9t84tr.cnu.mgjv at martien.heliotrope.home...
> On Tue, 16 Oct 2001 12:27:26 +0200,
> Laurent Pierron <Laurent.Pierron at loria.fr> wrote:
> > Hello Gurus,
[snip]
> > while (<>) {
> > if (/<BODY>/ .. /<\/BODY>/) {print; }
> > }
>
> Sorry to barge in, but that iperator, in this context, isn't the range
> operator, but the flip-flop [1]. Without more information, the python
> people here probably won't know what to look for. The way the flip-flop
> works is that the result of the expression A..B becomes true when A is
> true and stays true until B is true, after which the whole cycle can
> start again.
>
[snip]
> Martien Verbruggen
When I need this sort of thing, I usually implement it explicitly, with
a state variable:
import sys
inside = 0
for line in sys.stdin:
if line == '<body>\n': inside = 1
elif line == '</body>\n': inside = 0
if inside: print line,
(This will print '<body>' but not '</body>' -- tweak to taste, e.g.
with "continue")
Another version, using nested loops:
from sys import stdin
while 1:
line = stdin.readline()
if line == '<body>\n':
while 1:
line = stdin.readline()
if line == '</body>\n': break
print line,
elif not line:
break
A bit more obtuse, perhaps... :)
--
Magnus Lie Hetland
http://hetland.org
More information about the Python-list
mailing list