3

それに応じて移動したい配列に要素があります。

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

基本的には、「c」のインデックスを見つけて、「d」のインデックスに基づいて「d」の前に配置したいと思います。これらのキャラクターを例として使用しています。アルファベット順のソートとは関係ありません。

4

6 に答える 6

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));
于 2013-01-22T20:50:39.230 に答える
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
于 2013-01-22T20:31:49.963 に答える
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
于 2013-01-22T20:46:15.130 に答える
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へのこのリンクを参照してください。

于 2013-01-22T20:37:25.063 に答える
0

Uはこれを試すことができます

my $search = "element";
my %index;
@index{@array} = (0..$#array);
 my $index = $index{$search};
 print $index, "\n";
于 2013-01-22T20:26:07.830 に答える
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このコードは要素を削除しないことに注意してください。これを行うには、配列のインデックスを変更しているため、 cbeforeを挿入するか after を挿入するかを追跡する必要があります。d

于 2013-01-22T20:32:52.850 に答える