我在数组中有一个元素,我想相应地移动它。
@array = ("a","b","d","e","f","c");
基本上我想找到“c”的索引,然后根据“d”的索引再次将它放在“d”之前。我以这些字符为例。它与按字母顺序排序无关。
尝试使用数组切片执行此操作并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;
见 拼接()
a, b, c, d, e, f
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));
好吧,这是我的尝试:-)
#!/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
你可以试试这个
my $search = "element";
my %index;
@index{@array} = (0..$#array);
my $index = $index{$search};
print $index, "\n";
您可以使用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
before 还是 after d
,因为您正在更改数组的索引。
另一种使用数组切片的解决方案。这假设您知道数组中元素的期望。
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的此链接。