读取括号内的内容并比较perl中的数字

时间:2014-10-06 10:19:40

标签: perl

我的文件内容为:

(0872) "ss_current" (1 of 1)
(0873) "ss_current_6oct" (0 of 1)

我想读取每行文件,然后获取最后一个括号之间的内容,即

(1 of 1)
(0 of 1)

并且如果它们相等则比较数字,即“of”之前和之后的数字相等。 我的代码:

my @cs;
while (<$fh>) {
    if ($_ =~ /\((.*?)\)/) {
        my $temp = $1;
        print $temp, "\n";
    }
}

但是这会将内容设为08720873

3 个答案:

答案 0 :(得分:5)

你的正则表达式只是拿起第一组括号。更具体,您可以选择(1 of 1)(0 of 1)

while (<$fh>) {
    # \d+ means match one or more adjacent numbers
    # brackets capture the match in $1 and $2
    if ($_ =~ /\((\d+) of (\d+)\)/) {
        if ($1 == $2) {
           # they are equal! print out the line (or do whatever)
           # (the line is set to the special variable $_ while processing the file)
           print "$_";
        }
    }
}

答案 1 :(得分:0)

use strict;
use warnings;

open my $in, '<', 'in.txt';

while(<$in>){
    chomp;
    my ($first, $second) = /\((\d+) of (\d+)\)/;
    print "$first of $second\n" if $first == $second;
}

答案 2 :(得分:0)

你的正则表达式不够具体,因为每行中有多组括号。

可以使用正则表达式来匹配您想要使用backreferences的确切条件。

use strict;
use warnings;

while (<DATA>) {
    print if /\((\d+) of \1\)/;
}

__DATA__
(0872) "ss_current" (1 of 1)
(0873) "ss_current_6oct" (0 of 1)

输出:

(0872) "ss_current" (1 of 1)

请注意,这是一种高级技术,因为必须确保强制执行边界条件以避免以不期望的方式匹配子字符串。出于这个原因,如果你是初学者,我实际上建议使用一种类似警报外星人使用的技术。