Argh. I had the equivelent of that first off, but I'd used 1 for the section and para numbers so @captures contained a single element with the value 1 and I convinced myself that it was the match count.
Candidate for OT: most egregious programming error, ever maybe? :)
DWIM is Perl's answer to Gödel
| [reply] |
Well, it will place 1 (success flag) in @captures when there are no captures in the regexp, but that shouldn't matter since there shouldn't be any id_fields when there are no captures.
| [reply] [d/l] [select] |
a_ AWESOME. thank you both.
b_ the +1 on the substr should be cut. | [reply] |
On further investigation, it appears GrandFather's solution, as corrected by nmerriweather, is correct. ikegami's solution passes a 1 into @captures in the case of a successful match with no captures requested. This doesn't DWIM, and it proved to be a deal-breaker in my real-world task.
my $line = q{Convention_9841_12345678901234.txt};
my @captures;
print "\nIncorrect\n\n";
print_captures( incorrect( qr/Convention_(\d{4})_(\d{14})\.txt$/, $lin
+e ) );
print_captures( incorrect( qr/Convention_(\d{4})_\d{14}\.txt$/, $line
+) );
print_captures( incorrect( qr/Convention_\d{4}_\d{14}\.txt$/, $line )
+);
print_captures( incorrect( qr/Convention_((\d{4})_(\d{14}))\.txt$/, $l
+ine ) );
print_captures( incorrect( qr/^(.*Convention_(\d{4})_(\d{14})\.txt)$/,
+ $line ) );
print "\nCorrect\n\n";
print_captures( get_captures( qr/Convention_(\d{4})_(\d{14})\.txt$/, $
+line ) );
print_captures( get_captures( qr/Convention_(\d{4})_\d{14}\.txt$/, $li
+ne ) );
print_captures( get_captures( qr/Convention_\d{4}_\d{14}\.txt$/, $line
+ ) );
print_captures( get_captures( qr/Convention_((\d{4})_(\d{14}))\.txt$/,
+ $line ) );
print_captures( get_captures( qr/^(.*Convention_(\d{4})_(\d{14})\.txt)
+$/, $line ) );
sub incorrect {
my ($pattern, $line) = @_;
my @captures;
(@captures) = $line =~ m/$pattern/ or return;
return @captures;
}
sub get_captures {
my ($pattern, $line) = @_;
$line =~ m/$pattern/ or return;
return map {substr $line, $-[$_], $+[$_] - $-[$_]} (1 .. $#-);
}
sub print_captures {
my @captures = @_;
@captures ? print "captures: @captures\n" : print "no captures\n"
+;
}
| [reply] [d/l] [select] |
sub get_captures {
my ($pattern, $line) = @_;
my @captures = $line =~ m/$pattern/;
shift(@captures) if !$#+;
return @captures;
}
or
sub get_captures {
my ($pattern, $line) = @_;
my @captures = $line =~ m/($pattern)/;
shift(@captures);
return @captures;
}
| [reply] [d/l] [select] |
Your response and Grandfather's have solved an important problem for me on my day job. Thank you, fellow monks!
| [reply] |