Perl 在多个绑定运算符中捕获变量
Perl capture variables in multiple binding operators
有没有办法在 more than binding expression 中使用捕获组并捕获所有组?
#!/usr/bin/perl
use strict;
use warnings;
countDays(1,"2015-3-21","2016-3-24");
sub countDays {
die "Check formatting"
unless ($_[0] =~ m/([1-7])/ &&
$_[1] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})$/ &&
$_[2] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
# testing
print "\n\n\n\n\n\n\n";
}
这仅捕获最后三个组:</code>、<code>
和 </code>。</p>
<p>按照 Avinash Raj 的建议编辑预期输出:</p>
<pre><code>1
2015
3
21
2016
3
24
不,每次成功匹配都会重置所有捕获变量。但是你可以这样做:
sub countDays {
my @match1 = $_[0] =~ m/([1-7])/
and
my @match2 = $_[1] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})$/
and
my @match3 = $_[2] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})$/
or die "Check formatting";
print "@match1\n@match2\n@match3\n";
}
#!/usr/bin/env perl
use strict;
use warnings;
countDays(1,"2015-3-21","2016-3-24");
sub countDays {
my $countDays = join ',', @_;
die "Check formatting"
unless $countDays =~
m/([1-7]),(\d{4})-(\d{1,2})-(\d{1,2}),(\d{4})-(\d{1,2})-(\d{1,2})/;
# testing
print "\n\n\n\n\n\n\n";
}
有没有办法在 more than binding expression 中使用捕获组并捕获所有组?
#!/usr/bin/perl
use strict;
use warnings;
countDays(1,"2015-3-21","2016-3-24");
sub countDays {
die "Check formatting"
unless ($_[0] =~ m/([1-7])/ &&
$_[1] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})$/ &&
$_[2] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
# testing
print "\n\n\n\n\n\n\n";
}
这仅捕获最后三个组:</code>、<code>
和 </code>。</p>
<p>按照 Avinash Raj 的建议编辑预期输出:</p>
<pre><code>1
2015
3
21
2016
3
24
不,每次成功匹配都会重置所有捕获变量。但是你可以这样做:
sub countDays {
my @match1 = $_[0] =~ m/([1-7])/
and
my @match2 = $_[1] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})$/
and
my @match3 = $_[2] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})$/
or die "Check formatting";
print "@match1\n@match2\n@match3\n";
}
#!/usr/bin/env perl
use strict;
use warnings;
countDays(1,"2015-3-21","2016-3-24");
sub countDays {
my $countDays = join ',', @_;
die "Check formatting"
unless $countDays =~
m/([1-7]),(\d{4})-(\d{1,2})-(\d{1,2}),(\d{4})-(\d{1,2})-(\d{1,2})/;
# testing
print "\n\n\n\n\n\n\n";
}