Move element in perl array

I have an element in an array that I would like to move accordingly.

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

      

Basically, I would like to find the index "c" and then place it before "d" again based on the index "d". I am using these symbols as an example. This has nothing to do with sorting alphabetically.

+3


source to share


6 answers


Try to do this by slicing the array and List::MoreUtils

to find the indices of the array elements:

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;

      

See splicing ()



OUTPUT

a, b, c, d, e, f

      

+4


source


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));

      



+4


source


Well, here's my shot at this :-)

#!/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";

      

Will print

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

      

+3


source


U can try this

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

      

0


source


You can use splice

to insert an item at a specific index in an array. And a simple loop to find the indices you are looking 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;

      

Output:

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

      

Please note that this code does not remove the item c

. To do this, you need to keep track of whether you are inserting c

before or after d

, as you change the array indices.

0


source


Another solution using array slices. This assumes that you know the required elements in the array.

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;

      

See PerlMonks link for details .

0


source







All Articles