-1
爲了輸入數據,我有一個可變大小的散列,其中多個元素具有相似的名稱。哈希可能看起來像是一個例子;Perl簡單正則表達式捕獲組不捕獲
- wineName0 =>夏敦埃
- wineFull0 => 4.00
- wineHalf0 => 2.00
- wineName1 =>黑比諾
- wineFull1 => 16.00
- wineHalf1 => 8.00
- plateName0 =>側腹牛排
- plateCost0 => 14.00
- plateTemps0 =>允許
至於處理它們,我通過鍵迭代,具有正則表達式檢查它們,捕獲它們的數量,然後使用該編號,以抓住類似編號的元件,像這樣;
foreach $key (sort keys %in){
if($key =~ /wineName(\d+)/){
if($wineTable eq ""){
$wineTable = qq{
<tr>
<td colspan=3 class="label">Wines</td>
</tr>
};
}
$wineName = $key;
$in{$wineName} =~ s/\s/+/g;
$wineFull = "wineFull$1";
$wineHalf = "wineHalf$1";
$wineTable .= qq{
<tr>
<!-- $key -->
<td>$in{$wineName}</td>
<td>\$$in{$wineFull}</td>
<td>\$$in{$wineHalf}</td>
</tr>
};
}
if($key =~ /beerName(\d+)/){
if($beerTable eq ""){
$beerTable = qq{
<tr>
<td colspan=3 class="label">Beers</td>
</tr>
};
}
$beerName = $key;
$in{$beerName} =~ s/\s/+/g;
$beerFull = "beerFull$1";
$beerHalf = "beerHalf$1";
$beerTable .= qq{
<tr>
<!-- $key -->
<td>$in{$beerName}</td>
<td>\$$in{$beerFull}</td>
<td>\$$in{$beerHalf}</td>
</tr>
};
}
if($key =~ /plateName(\d+)/){
if($plateTable eq ""){
$plateTable = qq{
<tr>
<th>Name</th>
<th>Cost</th>
<th>Cook Temperatures</th>
</tr>
};
}
my $plateName = $key;
$in{$plateName} =~ s/\s/+/g;
my $plateCost = "plateCost$1";
my $plateTemp = "plateTemps$1";
if($in{$plateTemp}){
$in{$plateTemp} = 1;
}else{
$in{$plateTemp} = 0;
}
$plateTable .= qq{
<tr>
<!-- $key -->
<td>$in{$plateName}</td>
<td>\$$in{$plateCost}</td>
<td>$in{$plateTemp}</td>
</tr>
};
}
}
我的問題是,由於某些原因,/plateName(\d+)/
不捕獲。所以如果$key == "plateName1"
,$plateCost
結束等於「plateCost」,而不是「plateCost1」。我給出的散列鍵作爲示例是實際的例子。考慮到這一點,我需要幫助理解爲什麼葡萄酒的正則表達式起作用,而正則表達式不適用,因爲它們幾乎完全相同。
你可以分享你的具體正則表達式和數據的情況下,它不工作? –
@FedericoPiazza顯示的正則表達式和數據正是我正在使用的。 –
你期望輸出什麼?它似乎適用於我,它不會在循環的同一迭代中填充葡萄酒和盤子,因爲它在每個步驟中只處理一個鍵。 – choroba