2014-11-14 19 views
2

我有輸出readelf -Ws匹配以下正則表達式:使用命名的子表達式時可以複製%+哈希值嗎?

my $regex = qr{ ^\s+(?'Num'\d+): 
        \s+(?'Value'\w+) 
        \s+(?'Size'(?:\d+|0x[0-9a-fA-f]+)) 
        \s+(?'Type'\w+) 
        \s+(?'Bind'\w+) 
        \s+(?'Vis'\w+) 
        \s+(?'Ndx'\w+) 
        \s+(?'Name'\S+) 
       }x; 

...雖然它可能不是完美的,它適合我的需求不夠好。

理想的情況下,這將被使用的方式是:

while(<>) { 
    chomp; 
    m{${regex}} || next; 
    # an implicit assertion here is that length($+{Name}) > 0 
    if( $+{Type} =~ m{something} 
    && $+{Bind} =~ m{something} 
    ... 

...然而,%+得到第一個正則表達式後重挫。我不知道如何製作%+的散列副本。是否有可能,如果有的話,我會怎麼做?

顯然,下面可以做:

while(<>) { 
    chomp; 
    my ($Num, $Value, $Size, $Type, $Bind, $Vis, $Ndx, $Name) = ($_ =~ m{${regex}}); 
    next unless defined($Name); 

    if( $Type =~ m{something} 
    && $Bind =~ m{something} 
    ... 

...但我比較喜歡使用命名的子表達式,因爲它可以幫助正則表達式自我記錄。

回答

2
%captures = %+; 

use Data::Dumper qw(Dumper); 

local $_ = 'abc123'; 

my @captures; 
while (/(?'Letters'\pL+)|(?'Digits'\pN+)/g) { 
    my %captures = %+; 
    push @captures, \%captures; 
} 

print(Dumper(\@captures)); 

$VAR1 = [ 
      { 
      'Letters' => 'abc' 
      }, 
      { 
      'Digits' => '123' 
      } 
     ]; 

或者因爲只有定義的字段都存在,你可以使用

%captures = (%captures, %+); 

$captures{$_} = $+{$_} for keys %+; 

use Data::Dumper qw(Dumper); 

local $_ = 'abc123'; 

my %captures; 
while (/(?'Letters'\pL+)|(?'Digits'\pN+)/g) { 
    %captures = (%captures, %+); 
} 

print(Dumper(\%captures)); 

$VAR1 = { 
      'Letters' => 'abc', 
      'Digits' => '123' 
     }; 
+0

HRM。我發誓我試圖做明顯的事情,它留下'%捕獲'在未定義的狀態。我會再試一次,感謝迅速的迴應。 – 2014-11-14 17:59:50

+0

銖。有效。我不知道第一次出錯的地方,但現在工作正常。 – 2014-11-14 18:08:05

相關問題