Perl数组:模式匹配,然后移到另一个数组

时间:2019-05-06 14:28:52

标签: arrays regex perl hash

Perl:我想移动与模式匹配的数组的每个元素。

例如,我有下面的数组 @ array1 = {猫2,狗3#移动,老虎4#移动,狮子10}

现在我想将狗3,老虎4(作为模式#move匹配)移动到另一个数组,比如说@ array2

foreach $array (@array1) {
    if ($array =~ m/(./w*) (./d*)#move/) {
          push @array2, $1.$2;
    }

但是我想从array1中删除那些元素。预先感谢

4 个答案:

答案 0 :(得分:4)

有多种方法可以实现,因此受this answer的启发,这是另一种方法:使用grep保留所需的元素。由于Perl仅支持在某些情况下从要迭代的数组中删除元素,因此不需要您知道哪些情况是:)。

use strict; use warnings;
my @array1 = ("cat 2", "dog 3#move", "tiger 4#move", "lion 10");
my @array2;

@array1 = grep {    # We are going to search over @array1 and only keep some elements.
    if (/(.*)#move/) {  # If this is one we want to move...
        push @array2, $1;   # ... save it in array2...
        0;      # ... and do not keep it in array1.
    } else {
        1;      # Otherwise, do keep it in array1.
    }
} @array1;

# Debug output - not required
print "Array 1\n";
print join "\n", @array1;
print "\nArray 2\n";
print join "\n", @array2;
print "\n";

输出:

Array 1
cat 2
lion 10
Array 2
dog 3
tiger 4

答案 1 :(得分:1)

这是一种方法:

use feature qw(say);
use strict;
use warnings;
use Data::Printer;

my @array1 = ("cat 2", "dog 3#move", "tiger 4#move", "lion 10");
my @array2;
my @temp;
for my $elem (@array1) {
    if ( $elem =~ m/^(.*)#move/) {
        push @array2, $1;
    }
    else {
        push @temp, $elem;
    }
}
@array1 = @temp;

p \@array1;
p \@array2;

输出

[
    [0] "cat 2",
    [1] "lion 10"
]
[
    [0] "dog 3",
    [1] "tiger 4"
]

答案 2 :(得分:1)

这是List::UtilsBy中的extract_by函数的作用:

use strict;
use warnings;
use List::UtilsBy 'extract_by';
my @array1 = ("cat 2", "dog 3#move", "tiger 4#move", "lion 10");
my @array2 = map { s/#move//r } extract_by { m/#move/ } @array1;

答案 3 :(得分:0)

使用List :: Util

的可能解决方案
#!/usr/bin/env perl
#
use warnings;
use strict;
use List::Util qw(pairs pairgrep pairkeys);


my @array1 = ("cat 2", "dog 3#move", "tiger 4#move", "lion 10");

my $i=0;
my @indexList= map { ($i++, $_) } @array1;                     #build kv pairs

my @removed;
my @filtered=pairgrep { ($b =~ /#move/);} @indexList;          #grep kv pairs
push @removed, splice @array1, $_, 1 for (pairkeys @filtered); #splice and push

print "Modified original: @array1\n";
print "Removed elements: @removed\n";