Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl three dot operator ... examples

Tags:

perl

Can anybody show with some examples the exact difference between .. and ... operator?

From the perlop man page:

If you don't want it to test the right operand until the next evaluation, as in sed, just use three dots ("...") instead of two.

But what exactly this mean? I don't understand the perlop's example:

@lines = ("   - Foo",           "01 - Bar",           "1  - Baz",           "   - Quux" ); foreach (@lines) {     if (/0/ .. /1/) {         print "$_\n";     } } 

with ... will print the Baz - but why? More precisely, why is Baz not printed with two dots and only with ...?

like image 296
kobame Avatar asked Jun 13 '12 18:06

kobame


2 Answers

«...» doesn't do a flop check immediately after a true flip check.

With «..»,

  1. " - Foo"
    1. /0/ returns false.
    2. .. returns false.
  2. "01 - Bar"
    1. /0/ returns true. Flip!
    2. /1/ returns true. Flop!
    3. .. returns true (since the first check was true).
  3. "1 - Baz"
    1. /0/ returns false.
    2. .. returns false.
  4. " - Quux"
    1. /0/ returns false.
    2. .. returns false.

With «...»,

  1. " - Foo"
    1. /0/ returns false.
    2. ... returns false.
  2. "01 - Bar"
    1. /0/ returns true. Flip!
    2. ... returns true.
  3. "1 - Baz"
    1. /1/ returns true. Flop!
    2. ... returns true.
  4. " - Quux"
    1. /0/ returns false.
    2. ... returns false.
like image 50
ikegami Avatar answered Sep 21 '22 18:09

ikegami


If you have cases like /start/ .. /end/ with input

start some text end start some other text end 

the .. operator will process the end in the first line as soon as it reads it and will only print some text. The ... operator will not process the end on the first line so the other text will also be printed. Basically you can avoid stopping the range if the ending value is matched on the same line as the start. The ... postpones the check until the next iteration.

like image 32
kjp Avatar answered Sep 20 '22 18:09

kjp