How can I extract only those elements that I want to get from a Perl array?

Hey, I wonder how I can get this code to work. Basically I want to keep the lines $filenameas long as they contain $userin 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 that you can delete as delete $array[index], but I do not have an index with the type of loop that I know of.

+3
source share
4 answers

You can replace your loop:

@filenames = grep /$user/, @filenames;
+10
source

There is no way to do this when you use a loop foreach. But never mind. Correct to execute File :: Find in order to complete its task.

use File::Find 'find';

...

my @files;
my $wanted = sub {
    return unless /\Q$file/ && /\Q$user/;
    push @files, $_;
};

find({ wanted => $wanted, no_chdir => 1 }, '/home');

\Q .

, STDERR /dev/null

{
    local *STDERR;
    open STDERR, '>', '/dev/null';
    ...
}

.

+3

find, -path, , ,

#! /usr/bin/perl

use warnings;
use strict;

my $user = "gbacon";
my $file = "bash";

my $path = join " -a " => map "-path '*$_*'", $user, $file;
chomp(my @filenames = `find -H /home $path 2>/dev/null`);

print map "$_\n", @filenames;

, backticks ( , chomp) . split .

:

/home/gbacon/.bash_history
/home/gbacon/.bashrc
/home/gbacon/.bash_logout
+2

, splice.

my @foo = qw( a b c d e f );

splice( @foo, 3, 1 ); # Remove element at index 3.

splice. . perldoc.


, , for. , while.

, for parens . , .

A while , .

+2

Source: https://habr.com/ru/post/1746257/


All Articles