Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read File, Search for String, Print String Perl

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

$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 $&.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading