Samn has asked for the wisdom of the Perl Monks concerning the following question:

Replies are listed 'Best First'.
(jeffa) Re: Arranging arrays
by jeffa (Bishop) on Jul 19, 2002 at 01:21 UTC
    I would try a hash slice:
    use strict; my @array = (13, 27, 4, 18, 12, 6); my %hash; @hash{@array} = (0..$#array); my $index = $hash{18}; print "should be 18: ", $array[$index], "\n"; print "should be 4: ", $array[$index-1], "\n"; print "should be 12: ", $array[$index+1], "\n";
    But, this won't work if you have duplicate elements ... :( neat anyways.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Arranging arrays
by thelenm (Vicar) on Jul 19, 2002 at 01:20 UTC
    Does your value only occur once in the array? Can it occur as the very first element (in which case, what is the desired behavior)? Here is a code snippet that moves your desired element left in the list for a single occurrence. Remove the "and last" bit to do it for all occurrences. It also ignores the first element in the list.
    for (1..$#array) { @array[$_-1,$_] = @array[$_,$_-1] and last if $array[$_] == $value; }

    -- Mike

    --
    just,my${.02}

Re: Arranging arrays
by Abigail-II (Bishop) on Jul 19, 2002 at 12:45 UTC
    #!/usr/bin/perl use strict; use warnings 'all'; # Given an array and a value, move all elements equal to the # value one position to the left - do a block move if there # are consecutive elements of the value. my @array = (18, 18, 13, 27, 4, 18, 12, 6, 7, 18, 18, 18, 14, 15); + my $value = 18; print "@array\n"; @array [do {my $l; reverse map { $value eq $array [$_] ? do {$l = $_ unless defined $l; +$_ - 1} : do {$_ = $l if defined $l; unde +f $l; $_} } reverse 0 .. $#array}] = @array; print "@array\n"; __END__ 18 18 13 27 4 18 12 6 7 18 18 18 14 15 18 18 13 27 18 4 12 6 18 18 18 7 14 15