Perl Regex使用qr //

时间:2015-04-28 19:43:36

标签: regex perl replace

我正在创建一个解析文本文件的模块,我想要匹配的所有内容前面都有一个#但是当我尝试使用qr//时它不匹配任何东西。至少对我来说,最重要的是我需要它来遍历数组,我认为我不能使用$1或者它不能正常工作。 %$hash_ref是从数据库中提取的信息,其中键是列,值是值(显然)。文本文件包含#C3_WK_PH#SPECIAL_NOTES等字词。

sub replace {   
    open (my $in,  '<', "file.txt")  or die "cannot open $in: $!";
    open (my $out, '>', "file2.txt") or die "cannot open $out: $!";

    while (<$in>)
    {
            my @values = values %$hash_ref;
            my @keys   = keys %$hash_ref;
            my $count  = @keys;

            while ($count > 0) {
                my $thing  = $keys[$count];
                my $regexp = qr/#($thing)/;
                s/$regexp/$values[$count]/g;
                $count = $count - 1;
            }
            print $out $_;
    }
            close $in;
            close $out;
}

我知道我正在解析每一行$count次,但这是有目的的。

2 个答案:

答案 0 :(得分:4)

您的问题与qr//没有任何关系。 Perl中的数组是0索引的,因此第一次通过while ($count > 0) ...循环:

        my $thing = $keys[$count];

$thing设置为undef,因为@keys的最大元素是$count-1

        my $regexp = qr/#($thing)/;

$regexp设置为qr/#()/

        s/$regexp/$values[$count]/g;

删除输入中的所有#字符,将其替换为空格,并使其余的预期替换无意义。

如果你使用use warnings,你会得到一个关于这个问题的提示。

将循环编写为while ($count-- > 0) ...将起作用(并确保您处理$keys[0]$values[0]中的值),但考虑更多Perl-y迭代哈希的方式:

foreach my $thing (keys %$hashref) {
    my $replace = $hashref->{$thing};
    ...
}

while (my ($thing,$replace) = each %$hashref) {
    ...
}

答案 1 :(得分:2)

这与您所获得的相比有所简化,但它应该给出正确的想法:

// Color the links
var linkAttributes: NSMutableDictionary = NSMutableDictionary()
linkAttributes.setValue(self.appDelegate.variables.color320, forKey: NSForegroundColorAttributeName)

myTextView.linkTextAttributes = linkAttributes as [NSObject : AnyObject]

使用该代码,我能够使用#f,#b和#c成功地将文本转换为带有foo和bar以及黑猩猩的文本。

回到哈希引用,我有这个代码再次似乎工作正常。 (我现在已经离开了跟踪声明。)

%hash = ( 'f' => 'foo', 'b' => 'bar', 'c' => 'chimp' );
replace();

sub replace {   
    open (my $in, '<', "file.txt") or die "cannot open $in: $!";
    while (<$in>)
    {
            foreach my $thing (keys %hash) {
            s/#($thing)/$hash{$thing}/g;
            #print;
            }
            print;
    }
    close $in;
}

如果%hash = ( 'f' => 'foo', 'b' => 'bar', 'c' => 'chimp' ); $hash_ref = \%hash; replace(); sub replace { open (my $in, '<', "file.txt") or die "cannot open $in: $!"; while (<$in>) { foreach my $thing (keys %{$hash_ref}) { #my $regexp = qr/#($thing)/; print "REPLACING $thing WITH ${$hash_ref}{$thing}\nBEFORE: $_"; s/#($thing)/${$hash_ref}{$thing}/g; print "AFTER: $_"; } print; } close $in; } 语法不适合您,那么您需要告诉我们您是如何创建${$hash_ref}{$thing}的,因为该语法在这里工作正常。 ..: