How can I match variable length data between /FIRST/ .. /LAST/ (without including FIRST and LAST.
Well at first sight I can imagine two methods.
- Check the value of this expression. It's not just a boolean, it has a special format: it returns the sequence number of how many times in a row it has returned true. Also, the last value is special, as it has "E0" appended. That doesn't change the numerical value, "5E0" is as much a valid format for the number 5, as "5" is. For example:
for ('A' .. 'Z') {
if(my $counter = ($_ eq 'F' .. $_ eq 'J')) {
print "$counter: $_\n";
}
}
which prints:
1: F
2: G
3: H
4: I
5E0: J
As you can see, extracting the first (numerical 1) and last (string ends in "E0") time it'll match is easily recognized
- A second method is to have a flag for the first and second match:
for ('A' .. 'Z') {
if((my $first = $_ eq 'F') .. (my $last = $_ eq 'J')) {
printf "%s first:%s last:%s\n", $_, $first?'yes':'no', $last?'
+yes':'no', ;
}
}
which prints:
F first:yes last:no
G first:no last:no
H first:no last:no
I first:no last:no
J first:no last:yes
Also what is the difference between ".." and "..."?
Well... in some cases it is possible that the first and the last condition are both met on the first item. Sometimes you want to include that, in that case, use "..". Sometimes you want to skip it, for example if you want to match stuff between two identical delimiters. In the latter case, use "...", which skips the second test if you're on the first match — your "START".
A demonstration of the difference: the next code takes a range between two numbers that are divisible by 3, in the sequence 1 .. 8
- 2 dots:
for (1 .. 8) {
if((my $first = $_ % 3 == 0) .. (my $last = $_ % 3 == 0)) {
printf "%s first:%s last:%s\n", $_, $first?'yes':'no', $last?'
+yes':'no', ;
}
}
Result:
3 first:yes last:yes
6 first:yes last:yes
The start and the end condition are both met at the same time (divisible by 3), so the ranges are limited to one number.
- 3 dots:
for (1 .. 8) {
if((my $first = $_ % 3 == 0) ... (my $last = $_ % 3 == 0)) {
printf "%s first:%s last:%s\n", $_, $first?'yes':'no', $last?'
+yes':'no', ;
}
}
Result:
3 first:yes last:no
4 first:no last:no
5 first:no last:no
6 first:no last:yes
This one finds a range from 3 to 6. The second test is not tried when the first test is succesful.