perl

Why is grep command not showing any output in Perl?


I have an array @files in which I have multiple .txt files. I am trying to grep all the lines that have the pattern "/home/[a-z]+" from the starting of the lines in those files. I am trying the below approach:

my @lines = grep (/^\/home\/[a-z]+/, @files);
chomp(@lines);
my @line = uniq(@lines);

but I do not get anything in the output when I try to print @lines.

What am I doing wrong in the grep command?


Solution

  • Please see the following code sample which demonstrates an approach you have chosen.

    Note: there is no need to use uniq(@lines) as filesystem assumes uniq filenames in it's organization

    use strict;
    use warnings;
    use feature 'say';
    
    my @files = <DATA>;
    my @lines = grep( m!^/home/[a-z]+/!, @files);
    
    say @lines;
    
    __DATA__
    /home/alex/work/samples
    /home/philip/doc/asterix
    /home/maria/bin/quick_search.c
    /bin/grep
    /sbin/test
    

    Output

    /home/alex/work/samples
    /home/philip/doc/asterix
    /home/maria/bin/quick_search.c
    

    Sample code to filter matching pattern for list of files stored in an array @files.

    use strict;
    use warnings;
    use feature 'say';
    
    my @files = qw/abc.txt, bcd.txt, cde.txt/;
    my @lines;
    
    for my $file (@files) {
        my @temp;
        
        open my $fh, '<', $file
            or die "Couldn't open $file";
        @temp = grep( m!^/home/[a-z]+/!, <$fh>);    
        close $fh;
        
        @lines = (@lines, @temp);
    }
    
    chomp(@lines);
    
    say for @lines;