在perl数组中移动元素

时间:2013-01-22 20:17:38

标签: arrays perl

我在数组中有一个元素,我想相应移动。

@array = ("a","b","d","e","f","c");

基本上我想找到“c”的索引,然后再根据“d”的索引将它放在“d”之前。我用这些字符作为例子。它与按字母顺序排序无关。

6 个答案:

答案 0 :(得分:4)

尝试使用数组切片List::MoreUtils来查找数组元素索引:

use strict; use warnings;
use feature qw/say/;

# help to find an array index by value
use List::MoreUtils qw(firstidx);

my @array = qw/a b d e f c/;

# finding "c" index
my $c_index = firstidx { $_ eq "c" } @array;

# finding "d" index
my $d_index = firstidx { $_ eq "d" } @array;

# thanks ysth for this
--$d_index if $c_index < $d_index;

# thanks to Perleone for splice()
splice( @array, $d_index, 0, splice( @array, $c_index, 1 ) );

say join ", ", @array;

请参阅splice()

输出

a, b, c, d, e, f

答案 1 :(得分:4)

my @array = qw/a b d e f c/;
my $c_index = 5;
my $d_index = 2;

# change d_index to what it will be after c is removed
--$d_index if $c_index < $d_index;
splice(@array, $d_index, 0, splice(@array, $c_index, 1));

答案 2 :(得分:3)

嗯,这是我拍摄的照片: - )

#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw/ first /;

my @array = ("a","b","d","e","f","c");
my $find_c = 'c';
my $find_d = 'd';

my $idx_c = first {$array[$_] eq $find_c} 0 .. $#array;
splice @array, $idx_c, 1;

my $idx_d = first {$array[$_] eq $find_d} 0 .. $#array;
splice @array, $idx_d, 0, $find_c;

print "@array";

打印

C:\Old_Data\perlp>perl t33.pl
a b c d e f

答案 3 :(得分:0)

你可以试试这个

my $search = "element";
my %index;
@index{@array} = (0..$#array);
 my $index = $index{$search};
 print $index, "\n";

答案 4 :(得分:0)

您可以使用splice在数组中的特定索引处插入元素。还有一个简单的for循环来查找你寻找的索引:

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

for my $i (keys @a) { 
    if ($a[$i] eq 'c') { 
        $index = $i; 
        last; 
    } 
} 

if (defined $index) { 
    for my $i (keys @a) { 
        if ($a[$i] eq 'd') { 
            splice @a, $i, 1, $a[$index];
        } 
    } 
}

use Data::Dumper; 
print Dumper \@a;

<强>输出:

$VAR1 = [
          'a',
          'b',
          'c',
          'e',
          'f',
          'c'
        ];

请注意,此代码不会删除c元素。为此,您需要跟踪是否在c之前或之后插入d,因为您要更改数组的索引。

答案 5 :(得分:0)

使用数组切片的另一种解决方案。这假设您知道数组中所需的元素。

use strict;
use warnings;

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

my @new_order = (0, 1, 5, 2, 3, 4);
my @new_list = @array[@new_order];

print "\n";
print @new_list;

有关详细信息,请参阅PerlMonks的链接。