2015-08-15 62 views
0

有沒有辦法在多於綁定表達式中使用捕獲組並捕獲所有組?多個綁定運算符中的Perl捕獲變量

#!/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 "$1\n$2\n$3\n$4\n$5\n$6\n$6\n"; 

} 

這只是抓住了最後三組:$1$2$3

編輯爲預期產出爲阿維納什拉吉建議:

1 
2015 
3 
21 
2016 
3 
24 

回答

6

沒有,每一個成功的比賽重置所有捕獲的變量。但你可以這樣做:

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\[email protected]\[email protected]\n"; 
} 
1
#!/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 "$1\n$2\n$3\n$4\n$5\n$6\n$7\n"; 
}