Search code examples
arraysregexperl

How can I extract just the elements I want from a Perl array?


Hey I'm wondering how I can get this code to work. Basically I want to keep the lines of $filename as long as they contain the $user in the path:

        open STDERR, ">/dev/null";
        $filename=`find -H /home | grep $file`;
        @filenames = split(/\n/, $filename);
        for $i (@filenames) {
            if ($i =~ m/$user/) {
                #keep results
            } else {
                delete  $i; # does not work.    
            }
        }
        $filename = join ("\n", @filenames);
        close STDERR;

I know you can delete like delete $array[index] but I don't have an index with this kind of loop that I know of.


Solution

  • You could replace your loop with:

    @filenames = grep /$user/, @filenames;