ZebraSocks
ZebraSocks

Reputation: 85

Perl: How do I search a text file line by line to find a specific pattern?

I want to find a string STRING at the beginning of each line of a text file. So far, I have:

open(FILEHANDLE, "sample.txt")

while(my $line = <$FILEHANDLE>){
    if($line =~ PATTERN){
       doSomething();
    }
}

My question is: what do I put for PATTERN that will make my code work? I know that STRING will be at the beginning of each line of the text file, and that STRING will be followed by whitespace. STRING may change so it must be in a variable and not hardcoded in.

So far, I can only think of the Python way to do this:

PATTERN = r"^" + re.escape(STRING) + r"\s"
if re.search(PATTERN, line):
    doSomething();

How do I translate this to Perl?

Also, if this is bad Perl syntax, please let me know so I can fix it.

Upvotes: 2

Views: 9592

Answers (2)

Miller
Miller

Reputation: 35208

What you're looking for is quotemeta

use strict;
use warnings;
use autodie;

my $file = 'sample.txt';
my $literal_string = '...';

open my $fh, '<', $file;

while (my $line = <$fh>){
    if ($line =~ /^\Q$literal_string\E/){
       doSomething();
    }
}

Upvotes: 1

Paul
Paul

Reputation: 27493

You were almost there, just need to know that . is string concatenation, not +. and that quotemeta() does string escaping.

my $pat = "^".quotemeta($string)."\s" ;
while(my $line = <$FILEHANDLE>){
  if($line =~ /$pat/){
    doSomething();
  } 
}

Upvotes: 4

Related Questions