我有一個散列,其中的鍵和值來自正則表達式中的匹配。我無法提取給定鍵的值。爲了簡潔和對問題的磨練,我的這篇文章的第一版本試圖將我的程序僅刪除到相關部分,但這還不夠,所以這裏還有更多。變量和文件名已被修改,但語法爲真。雖然具體的正則表達式是不相關的,但我已經根據請求包含了它們。爲什麼我的Perl變量在if()塊之外有正確的值?
use strict;
my %Hash =();
my $logName = "MyLogName.Log";
open (LOG, '<', $logName) or die ("Couldn't open log ".$logName);
while (my $line = <LOG>) {
chomp $line;
if ($line =~ m/.*-t\s+(.+?),\s+(.+?)$/ix) {
# This print statement shows that I have correctly extracted what I want.
print ("Key::".$1."::Value::".$2."\n");
my $key = $1;
chomp $key;
my $value = $2;
chomp $value;
$Hash{$key} = $value;
}
}
close LOG;
#This shows the hash has been filled correctly. It shows all the keys and values
# I expect to see.
while ((my $newkey, my @newvalue) = each %Tests) {
print "Key##".$newkey."##NewValue:".$Tests{$newkey}."\n";
}
open (FILE, '<', "file.csv') or die ("Couldn't open csv file");
while (my $newLine = <FILE>) {
chomp $newLine;
if ($newLine =~ m/^(.+?),\s+(.+?)\s*?(.+?)$/ix) {
#This print statment verifies I've captured them correctly
print $1."::".$2."::".$3."\n";
my $val1 = $1;
my $val2 = $2; #This is the same as the key in %Hash
my $val3 = $3;
#For good measure...
print $val1."::".$val2."::".$val3."\n";
my $oldVal = $Hash{$val2};
print "oldVal::".$Hash{$val2}." "; #This line prints only the space
print "\$oldVal::".$oldVal."\n"; #This line prints only the newline
# Intent: put oldVal, val1, and val3 in an array and replace the old value
# in %Hash with the array, so I'd have a hash of arrays.
}
}
close FILE;
我在Cygwin中使用Perl v5.10.1。打印語句驗證從第一個文件讀取的密鑰與從第二個文件讀取的密鑰相同;正則表達式正是我想要的。散列是全局的。爲什麼在給定正確密鑰的情況下,這些打印語句最後會從散列中提取值?
運行這在調試器中使用「X」命令轉儲哈希值和鍵確認:1)哈希包含您期望的密鑰,以及b)密鑰確實相同。 – 2010-10-27 21:39:28
難道你的'$ value'在第二個塊的末尾超出了範圍?你在它超出範圍之前檢查它的值,對吧? – CanSpice 2010-10-27 21:56:08
我不知道你在做什麼。你爲什麼捕捉空弦? – 2010-10-28 00:13:47