no1 no1 - 6 months ago 15
Perl Question

using unix commands like grep and sed for the perl array

How do I grep for certain patterns in a perl array and use sed command and save output as another array,like below one

my @modifiedfiles=`echo @files | grep -E '(DataFiles|Pfgas|Startups)' | sed -e 's/.*something//g; s/#.*$//g;'`

Answer

You don't - it makes no sense :)

Perl has grep and map builtin:

my @filteredfiles = grep { /(DataFiles|Pfgas|Startups)/ } @files;
my @modifiedfiles = map { s/.*something//g; s/#.*$//g; $_ } @filteredfiles;

Also possible in one step:

my @modifiedfiles =
    map { s/.*something//g; s/#.*$//g; $_ }
    grep { /(DataFiles|Pfgas|Startups)/ } @files;

But Perls grep and map behave differently from the command line grep and map. See the documentation for details:

If you really want to do it anyway, it's possible with something like:

use IPC::Open2;

$pid = open2(\*CHLD_OUT, \*CHLD_IN,
    "grep  -E '(DataFiles|Pfgas|Startups)' | sed -e 's/.*something//g; s/#.*$//g;"
);

for my $file (@files) {
    print CHLD_OUT $file."\n";
    my $result_fn = <CHLD_IN>;
    chomp $result_fn;
    push @modifiedfiles, $result_fn;
}

No, you don't want to this :) It has lots of drawbacks and a high risk of failing. I assume the script will even start to block if grep filtered out a file.