Question

I have heard and read about flip-flops with regular expressions in Perl and Ruby recently, but I was unable to find how they really work and what the common use cases are.

Can anyone explain this in a language-agnostic manner?

Now that I understand what it is, and how it works, I would rephrase the question to be simply: What is a flip-flop operator?

Was it helpful?

Solution

The flip-flop operator in Perl evaluates to true when the left operand is true, and keeps evaluating to true until the right operand is true. The left and right operand could be any kind of expression, but most often it is used with regexes.

With regexes, it is useful for finding all the lines between two markers. Here is a simple example that shows how it works:

use Modern::Perl;

while (<DATA>)
{
    if (/start/ .. /end/)
    {
        say "flip flop true: $_";
    }
    else
    {
        say "flip flop false: $_";
    }
}

__DATA__
foo
bar
start
inside
blah
this is the end
baz

The flip flop operator will be true for all lines from start until this is the end.

The two dot version of the operator allows first and second regex to both match on the same line. So, if your data looked like this, the above program would only be true for the line start blah end:

foo
bar
start blah end
inside
blah
this is the end
baz

If you don't want the first and second regexes to match the same line, you can use the three dot version: if (/start/ ... /end/).

Note that care should be taken not to confuse the flip-flop operator with the range operator. In list context, .. has an entirely different function: it returns a list of sequential values. e.g.

my @integers = 1 .. 1000; #makes an array of integers from 1 to 1000. 

I'm not familiar with Ruby, but Lee Jarvis's link suggests that it works similarly.

OTHER TIPS

Here is a direct Ruby translation of @dan1111's demo (illustrating that Ruby stole more than the flip_flop from Perl):

while DATA.gets
  if $_ =~ /start/ .. $_ =~ /end/ 
    puts "flip flop true: #{$_}"
  else
    puts "flip flop false: #{$_}"
  end
end

__END__
foo
bar
start
inside
blah
this is the end
baz

More idiomatic ruby:

DATA.each do |line|
  if line =~ /start/ .. line =~ /end/ 
    puts "flip flop true: #{line}"
  else
    puts "flip flop false: #{line}"
  end
end

__END__
foo
bar
start
inside
blah
this is the end
baz
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top