Perl: removing array elements and resizing an array

Im trying to filter an array of terms using another array in Perl. I have Perl 5.18.2 on OS X, although the behavior is the same if I am use 5.010. Here is my basic setup:

#!/usr/bin/perl
#use strict;
my @terms = ('alpha','beta test','gamma','delta quadrant','epsilon',
             'zeta','eta','theta chi','one iota','kappa');
my @filters = ('beta','gamma','epsilon','iota');
foreach $filter (@filters) {
    for my $ind (0 .. $#terms) {
        if (grep { /$filter/ } $terms[$ind]) {
            splice @terms,$ind,1;
        }
    }
}

This works to pull strings matching various search queries, but the length of the array does not change. If I write out the resulting array @terms, I get:

[alpha]
[delta quadrant]
[zeta]
[eta]
[theta chi]
[kappa]
[]
[]
[]
[]

As expected, the print scalar(@terms)gets the result 10.

I want to get a resulting array of length 6, with no four empty elements at the end. How to get this result? And why isnt the array shrinking given that the perldocsplice page says: "The array grows or shrinks as needed."

(Im Perl, , : " ...?", , , .)

+4
2

, . grep , , , :

#!/usr/bin/perl

use strict;

my @terms = ('alpha','beta test','gamma','delta quadrant','epsilon',
           'zeta','eta','theta chi','one iota','kappa');
my @filters = ('beta','gamma','epsilon','iota');

my %filter_exclusion = map { $_ => 1 } @filters;

my @filtered = grep { !$filter_exclusion{$_} } @terms;

print join(',', @filtered) . "\n";

, , %filter_exclusion.

. :

my $filter_exclusion = join '|', map quotemeta, @filters;

my @filtered = grep { !/$filter_exclusion/ } @terms;
+7

, , : , , 0.. $#, $ind . grep { ... } $array[ $too_large ], Perl $_ grep, undef .

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my @terms = ('alpha', 'beta test', 'gamma', 'delta quadrant', 'epsilon',
             'zeta', 'eta', 'theta chi', 'one iota', 'kappa');
my @filters = qw( beta gamma epsilon iota );

for my $filter (@filters) {
    say $filter;
    for my $ind (0 .. $#terms) {
        if (grep { do {
            no warnings 'uninitialized';
            /$filter/
        } } $terms[$ind]
        ) {
            splice @terms, $ind, 1;
        }
        say "\t$ind\t", join ' ', map $_ || '-', @terms;
    }
}

$terms[$ind] =~ /$filter/ grep, , , .

0

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


All Articles