Perl:哈希和正则表达式中的键问题

问题描述:

对不起,发布了另一个类似于我之前发布的问题的问题。我意识到我的问题不是很清楚,可能会导致对答案的误解。所以我想重写它并再次提问。Perl:哈希和正则表达式中的键问题

我的任务是在2档(基本配置文件和配置文件)读取。这两个文件可以有任意数量的行。线的顺序不需要按顺序排列。 “!”之后我需要忽略一些事情和“^”。但是,我被卡在忽略“!”的部分和“^”。我能够将每行存储在一个散列中的键(没有“!”或“^”之后的东西),但是当我比较时它失败了。例如,如果文件中有一行“hello!123”,我需要在散列中只存储“hello”,并将字符串“hello”与另一个散列中的另一个键相比较。如果另一个散列中有“hello”键,我需要将其打印出来或放入另一个散列。我的程序只能从行“hello!123”放入“hello”,但在与另一个散列中的另一个键进行比较时,该部分失败。

我已经写另一短的程序,只需要在用户输入后取出的东西检查了我的正则表达式“!”和“^”符号并与另一个散列的另一个键进行比较。

这里是我的错误代码:

my %common=(); 
my %different=(); 
#open config file and load them into the config hash 
open CONFIG_FILE, "< script/".$CONFIG_FILENAME or die; 
my %config; 
while (<CONFIG_FILE>) { 
    chomp $_; 
    $_ =~ s/(!.+)|(!.*)|(\^.+)|(\^.*)//; 
    $config{$_}=$_; 
    print "_: $_\n"; 
    #check if all the strings in BASE_CONFIG_FILE can be found in CONFIG_FILE 
    $common{$_}=$_ if exists $base_config{$_};#stored the correct matches in %common 
    $different{$_}=$_ unless exists $base_config{$_};#stored the different lines in %different 
} 
close(CONFIG_FILE); 

没有人之前有同样的问题吗?你做什么来解决它?

+0

它在“与其他散列中的另一个键进行比较时的部分失败”中究竟有多失败?你的意思是每行都打印出来吗? (这是因为打印没有条件。)你的正则表达式替换会起作用,但最好写成's /[!^].*//;'。 – Qtax 2012-02-23 09:30:34

我不完全确定你的问题是樱花,但我想这可能是因为你应该在$config$base_config之间找不到匹配。我怀疑这可能是因为前/后的空白,并建议你写

while (<CONFIG_FILE>) { 
    s/[!^].*//;   # Remove comments 
    s/^\s+//;    # and clear leading 
    s/\s+$//;    # and trailing whitespace 
    next if length == 0; # Ignore empty lines 
    $config{$_} = $_; 
    print "_: $_\n"; 
    if ($base_config{$first}) { 
    $common{$first} = $first; 
    } 
    else { 
    $different{$first} = $first; 
    } 
} 

你还需要确保$base_config面前你比较它的值相同的待遇。

+0

是它可以正常使用。现在,我没有考虑前/后空白,并导致错误。感谢您的帮助! – Sakura 2012-02-24 01:37:24

+0

@Sakura我注意到我的代码中有一些错误。首先,可能有一行之间的空白数据的末尾和注释会被错误地保留下来;第二,在删除所有注释和空白之后,可能没有任何剩余,并且空字符串不应该被存储为有效密钥。强烈建议您将更改复制到您自己的代码中。对于这些错误,我表示歉意。 – Borodin 2012-02-24 10:43:15

my %common=(); 
my %different=(); 
#open config file and load them into the config hash 
open CONFIG_FILE, "<", "script/".$CONFIG_FILENAME or die; 
my %config; 
while (<CONFIG_FILE>) { 
    chomp; 

    my ($first,$last) = (split(\!| \^,$_,2); 

    $config{$first}=$first; 

    print "_: $first\n"; 

    #check if all the strings in BASE_CONFIG_FILE can be found in CONFIG_FILE 
    if (exists $base_config{$first}) { 
      $common{$first}=$first; #stored the correct matches in %common 
    } else { 
     $different{$first}=$first; #stored the different lines in %different 
    } 
} 
close(CONFIG_FILE); 

这是我采取的办法 - 请注意代码是未经测试,我刚刚醒来:)你可能在猜测来解决一两件事情(分割线附近。 ..)但这个想法是有效的。

+0

Thansk为您的快速反应!我修复了拆分附近的语法错误。但是,我仍然得到与我的代码相同的错误。 > Sakura 2012-02-23 07:52:00

+1

'(分割(\ | \ ^,$ _,2);!'是无稽之谈,我怀疑你的意思是'拆分/ | \^/,$ _,2;' – Borodin 2012-02-23 09:32:47