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

时间:2012-02-23 07:14:30

标签: regex string perl file hash

很抱歉发布与我之前发布的问题类似的其他问题。我意识到我的问题不是很清楚,可能会导致答案中出现一些误解。所以我想重新改写它并再次提问。

我的任务是读入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);

有没有人和我之前有同样的问题?你怎么做才能解决它?

2 个答案:

答案 0 :(得分:0)

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);

这是我采取的方法 - 请注意代码是未经测试的,我只是刚刚醒来:)你可能需要修复一些事情(在猜测的分界线附近......)但是这个想法是有效的。

答案 1 :(得分:0)

我不确定你的问题是什么樱花,但我认为你应该找到$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具有相同的处理方式。