Mark Mark - 8 months ago 34
Perl Question

Perl $1 variable not defined after regex match

This is probably a very basic error on my part, but I've been stuck on this problem for ages and it's driving me up the wall!

I am looping through a file of Python code using Perl and identifying its variables. I am using a Perl regex to pick out substrings of alphanumeric characters in between spaces. The regex works fine and identifies the lines that the matches belong to, but when I try to return the actual substring that matches the regex, the capture variable

is undefined.

Here is my regex:

if ($line =~ /.*\s+[a-zA-Z0-9]+\s+.*/) {
print $line;
print $1;

And here is the error:

x = 1
Use of uninitialized value $1 in print at ./ line 7, <> line 2.

As I understand it,
is supposed to return
. Where is my code going wrong?


You're not capturing the result:

if ($line =~ /.*\s+([a-zA-Z0-9]+)\s+.*/) {

If you want to match a line like x = 1 and get both parts of it, you need to match on and capture both with parenthesis. A crude approach:

if ( $line =~ /^\s* ( \w+ ) \s* = \s* ( \w+ ) \s* $/msx ) {
    my $var = $1;
    my $val = $2;