Get the line number of a regex match

This example shows how to use File::Slurper, Text::LineNumber, and pos to get line number offsets in a file which is read in as a block of text. This example program searches a C file for the bsearch function and then prints the line numbers.

#!/home/ben/software/install/bin/perl
use warnings;
use strict;
use utf8;
use File::Slurper 'read_text';
use Text::LineNumber;
my $file = "test.c";
my $c = read_text ($file);
my $tln = Text::LineNumber->new ($c);
while ($c =~ /\b(bsearch[^;]*);/g) {
    my $match = $1;
    my $pos = pos ($c) - length ($match);
    my $line = $tln->off2lnr ($pos);
    print "$file:$line: '$match'.\n";
}

(download)

The output of this on the test code looks like this.

test.c:17: 'bsearch (c, d->b, 1, sizeof (* (d->b)), mystrcmp)'.
test.c:18: 'bsearch (c, d->b, 1, sizeof (char *), mystrcmp)'.

The example code (non-functioning) is this.

/* This C code is not intended to compile, it is for testing a search
   program. */
#include <stdlib.h>
int mystrcmp (const void * x, const void * y)
{
    return -1;
}
struct a {
    char * b;
};
int main ()
{
    struct a * d;
    char * c;
    void * e;
    void * f;
    e = bsearch (c, d->b, 1, sizeof (* (d->b)), mystrcmp);
    e = bsearch (c, d->b, 1, sizeof (char *), mystrcmp);
    return 0;
}

(download)


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer