Perl regexp \A doesn't match start of file?

Viewed 199

I am iterating through a file line by line, picking out lines that start with asterix: *. My simple regexp works for all lines except the very first line of the file.

The DESIRED BEHAVIOR is: the regexp should correctly match lines that start with an asterix.

The ACTUAL BEHAVIOR is: if the asterix occurs on the very first line of the file, the regexp fails to match.

My DEBUGGING ATTEMPTS include:

  1. Add empty line at start of file. RESULT: The formerly missed line, now at second line of file, is correctly matched by regexp.

  2. Remove \A from regexp, just match against asterix. The first line of file now correctly is matched by regexp.

  3. Try using ^ instead of \A. First line of file still fails to match.

MINIMAL CODE TO REPRODUCE:

   while (<$input_fh>) {
     chomp;
     $line = $_;
     if ($line =~ /\A\*/) {
        ...
     }
  }

The input file consists of lines of text that may or may not start with an asterix.

1 Answers

/\A\*/ matches start of string, and then an asterisk character.

You need to match any symbols between the start and an asterisk.

Use

/\A.*?\*/

See proof

Explanation

--------------------------------------------------------------------------------
  \A                       the beginning of the string
--------------------------------------------------------------------------------
  .*?                      any character except \n (0 or more times
                           (matching the least amount possible))
--------------------------------------------------------------------------------
  \*                       '*'
Related