Namrata Purvimath Namrata Purvimath - 1 month ago 5
Perl Question

How to ignore first word of a line while grepping from a file in perl?

sub get_info () {

open(FILE,"file.txt") or die "Could not open file";
my @list = grep /\bWarning\b/, <FILE>;
$count = 0;
chomp @list;
$list[$count] =~ s/^\S+\s*//;
#do something;
$count++;
}

file.txt -
Warning: New layer 256 is added
Warning: Layer deleted
Warning: New layer 301 is added


I want to ignore the 'Warning' word from every line.

But it is hiding the word 'Warning' only from the first sentence.

Am I incrementing $count properly?

Answer

This is because you are doing the replacement only for $count=0. Therefore only first index is getting modified.

$list[$count] =~ s/^\S+\s*//g;

You have not used any loop so count does not make sense.

Solution:

#!/usr/bin/perl
use strict;
use warnings;

sub get_info{    
    open(FILE,"file.txt") or die "Could not open file";
    my @list = grep /\bWarning\b/, <FILE>;
    my $count = 0;
    foreach (@list) {
        $list[$count] =~ s/^\S+\s*//g;
        $count++;
    }
    print @list;
    #do something;
}

get_info();

Output:

New layer 256 is added
Layer deleted
New layer 301 is added

Improvements: Used 3 args open, removed grep and search replace, added while loop to read file line by line

#!/usr/bin/perl
use strict;
use warnings;

my @list;
sub get_info{
    open(my $fh, "<", "file.txt") or die "Could not open file: $!";
    while(<$fh>){
        chomp;
        if (/^Warning:(.*)/){
            push @list, $1;
        }
    }
    print @list;
    #do something;
}

get_info();
Comments