ptkwt@aracnet.com (Phil Tomson) wrote:
Seems to work and be nestable, as in the usage here:
ff = FlipFlop.new
ff2= FlipFlop.new
f = File.open(‘filename’)
f.each_line {|l|
ff.from(l=~/BEGIN/, l=~/END/) do
#inside the BEGIN … END block
ff2.from(l=~/def/,l=~/end/) do
#inside def … end block
puts l
end
end
}
But it’s more cumbersome having to predeclare all the FlipFlops.
Now that raises an interesting point. Say you had this input:
···
BEGIN
def baz
#oops, syntax error
END
BEGIN
#we shouldn’t see this line
END
Your code above would break with it (at least, wouldn’t produce what I
think most people would expect it to). So would the builtin flipflop
syntax. However, it’s easy to solve with a slight modification to the
FlipFlop class:
class FlipFlop
def initialize
@in_range = false
end
def from(start_cond, end_cond)
if start_cond
@in_range = true
@nested = FlipFlop.new
end
yield @nested if @in_range
@in_range = false if end_cond
end
end
ff = FlipFlop.new
f = File.open(‘test’)
f.each_line {|l|
ff.from(l=~/BEGIN/, l=~/END/) do
>nested>
nested.from(l=~/def/,l=~/end/) do
#inside def … end block
puts l
end
end
}