为什么我的Perl变量在if()块之外没有正确的值?

时间:2010-10-27 21:33:35

标签: perl hash scope

我有一个哈希,其中键和值来自正则表达式中的匹配。我很难在给定键的情况下提取值。为了简洁和磨练问题,我在这篇文章的第一个版本试图将我的程序仅删除到相关部分,但这还不够,所以这里还有更多。变量和文件名已被修改,但语法为真。虽然具体的正则表达式是无关紧要的,但我已根据要求将它们包括在内。

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。 print语句验证从第一个文件读取的密钥与从第二个文件读取的密钥相同;正则表达式完全符合我的要求。哈希是全局的。在给定正确的密钥的情况下,为什么最后那些print语句不从哈希中提取值?

3 个答案:

答案 0 :(得分:2)

您当然可以使用正则表达式匹配变量作为哈希键。这些字符串和任何其他字符串之间没有区别。如果你想要一个更完整的答案,我建议发布你的实际正则表达式以及导致问题的一些示例输入行。

答案 1 :(得分:2)

完成正常的调试过程。确保价值符合您的预期。

检查散列是否包含您认为具有的键和值:

 use Data::Dumper;

 print Dumper( \%Hash );

在您的代码中,检查每一步的值:

 if ($line2 =~ m/    ( )  ( )  ( )  /ix {
   my $key = $1;
   chomp $key;
   print "key is [$key]\n";
   my $value = $Hash{$key};
   print "value is [$value]\n";
   }

我敢打赌,你会发现$ value设置得很好,所以你的问题就是其他的东西,比如$value是词法范围的,而你没有对它做任何事情,所以它就消失了块结束。您可能希望将该值分配给该块上方:

 my $value = do {
   if ($line2 =~ m/    ( )  ( )  ( )  /ix {
      my $key = $1;
      chomp $key;
      print "key is [$key]\n";
      $Hash{$key};
      }
   };

 print "value is [$value]\n";

答案 2 :(得分:-2)

use strict;
use warnings;