Search code examples
regexperltail

In Perl, using File::Tail trying to grep pattern using regex, but $1 unintialised


I am trying to continuously tail a growing file, and using regex to extract information whenever new lines are added to the file, but $1 does not seem to like it.

Code

#!/usr/bin/perl
$| = 1;
use strict;
use warnings;

use File::Tail;

my $file=File::Tail->new(
        name=>"sample.txt",
        maxinterval=>1,
        interval=>0.05);

while (defined(my $line=$file->read))
{
        chomp($line);
        print "$line\n";
        if ($line =~ m/ls/)
        {
                print $1;
                print "MATCH\n";
        }
}

Input to sample.txt, entered in bash shell

echo "test1" >> sample.txt
echo "test2" >> sample.txt
echo "test3" >> sample.txt
echo "testls4 >> sample.txt

Output

test1
test2
test3
testls4
Use of uninitialized value $1 in print at test.pl line 19.
MATCH

clearly, there is a match, since MATCH was displayed on the output, but why is $1 still uninitialised? Strangely enough, outside of the while loop, I have no problems with $1


Solution

  • $1 and similar contain the strings captured by parentheses. You need to surround your regex pattern with parentheses to have $1 contain what you matched.