Home > Net >  Read File, Search for String, Print String Perl
Read File, Search for String, Print String Perl

Time:04-12

I am trying to read a file, search for a string using regex and print the string that matches that regex. I do not want the entire line that the regex match has found, just the string match.

use warnings;
use strict;

my $src = 'D:\Scripts\file.c';

# open source file for reading
open(SRC,'<',$src) or die $!;

while(my $row = <SRC>){
    if ($row =~ /[0-9]{2}\.[0-9]{2}\.[0-9]{3}\.[a-z,0-9]{2}|[0-9]{2}\.[0-9]{2}\.[0-9]{3}\.[a-z,0-9]{3}/){
        print "$1 \n";
    }
}

close(SRC);

My above example does not work. I am getting Use of uninitialized value $1 in concatenation (.) or string at script.pl line 12, line 8. I am running this on Windows 10 command line with Perl 5.32.1.

CodePudding user response:

$1 is the text captured by the first capture ((...)) in your pattern. Your pattern has no captures, so $1 becomes undef on a match.

If you wish to print the matched text, use $&.

  • Related