我有一个散列,其中的键和值来自正则表达式中的匹配。我无法提取给定键的值。为了简洁和对问题的磨练,我的这篇文章的第一版本试图将我的程序仅删除到相关部分,但这还不够,所以这里还有更多。变量和文件名已被修改,但语法为真。虽然具体的正则表达式是不相关的,但我已经根据请求包含了它们。为什么我的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