0

I am having trouble with a PERL Script I'm writing to take 1 smaller file and compare each line with the contents of a larger file. I am using a positive look-behind regex statement to find the match and give me just the rest of the line.

When I run the code I see all of the elements of @elements print, with no matches printed until the last line. Without displaying sensitive data this is what I see.

$element[0]

.

.

.

$element[30]

[match]

.

.

.

.

.

The matches for element[30] list perfectly, but I am expecting this to happen for each element, not just last element in the array. Here is my code:

    use strict;
    use warnings;
    open(my $in, "<", "call_types.txt");
    my @elements = <$in>;
    close $in;
    open(my $in, "<", "DNIS.cfg");
    my @dnis = <$in>;
    close $in;

    foreach my $call(@elements){
        print "$call\n";
        foreach my $dn(@dnis){
            if($dn =~ /(?<=$call ).*/){ 
                 print "$&\n";
            }
        }
        print "\n";
    }

1 Answer 1

1

You need to

chomp @elements

before you use the contents, otherwise the contents will match only if the text appears at the end of lines in @dnis.

There is also no point in using a look-behind, and you need to be careful of any regex metacharacters the data may contain. You probably need

print "$1\n" if $dn =~ /(\Q$call\E.*)/;
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much! Chomping the array worked, and thanks for the tip on escaping the variable. I didn't even consider the fact that the variable could contain inadvertent regex commands.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.