Search code examples
perlzcat

zcat working in command line but not in perl script


Here is a part of my script:

foreach $i ( @contact_list ) {

    print "$i\n";

    $e = "zcat $file_list2| grep $i";
    print "$e\n";

    $f = qx($e);
    print "$f";                                       
}

$e prints properly but $f gives a blank line even when $file_list2 has a match for $i.

Can anyone tell me why?


Solution

  • Always is better to use Perl's grep instead of using pipe :

    @lines = `zcat $file_list2`;    # move output of zcat to array
    die('zcat error') if ($?);      # will exit script with error if zcat is problem
    # chomp(@lines)                 # this will remove "\n" from each line
    
    foreach $i ( @contact_list ) {
    
        print "$i\n";
    
        @ar = grep (/$i/, @lines);
        print @ar;
    #   print join("\n",@ar)."\n";      # in case of using chomp
    }
    

    Best solution is not calling zcat, but using zlib library : http://perldoc.perl.org/IO/Zlib.html

    use IO::Zlib;
    
    # ....
    # place your defiiniton of $file_list2 and @contact list here.
    # ...
    
    $fh = new IO::Zlib; $fh->open($file_list2, "rb")
        or die("Cannot open $file_list2");
    @lines = <$fh>;
    $fh->close;
    
    #chomp(@lines);                    #remove "\n" symbols from lines
    foreach $i ( @contact_list ) {
    
        print "$i\n";
        @ar = grep (/$i/, @lines);
        print (@ar);
    #   print join("\n",@ar)."\n";    #in case of using chomp
    }