Perl – Use of uninitialized value in pattern match (m//)


I'm getting this error even though I have declared my regex variable.

my $pattern = '(Cat\.\sNo\.\s\d+)';

Later in my code I use then $pattern.

if ($page =~ /$pattern/)
  push(@array, $element);

But when I run my code it gives me the below error, and continues to run successfully:

Use of uninitialized value in pattern match (m//)

A search on Google for this error seems to point to scenarios where the variable has not been initialised, although in my case it would seem I have initialised it already?

Best Solution

That message is not telling you that $pattern is uninitialized; it's telling you that $page is uninitialized. If you're expecting that $page might be uninitialized, and that's O.K., then you can bypass the warning, and make things clear for future readers of the source-code, by writing this:

if (defined($page) && ($page =~ /$pattern/))
Related Question