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.
source to share
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
source to share
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
source to share
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.
source to share