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

I have an array , and i want to put an element if present in that array to the first position. How to do this.

For example if my array is
my @array = ("apple","ball","cat","dog","elephant");
and if my required element is dog, then my final array should be dog,apple,ball,cat,elephant.

Replies are listed 'Best First'.
Re: Putting an elemnt in first position in array.
by marto (Cardinal) on Jun 14, 2010 at 10:44 UTC
Re: Putting an elemnt in first position in array.
by JavaFan (Canon) on Jun 14, 2010 at 10:48 UTC
    perldoc -f unshift
Re: Putting an elemnt in first position in array.
by salva (Canon) on Jun 14, 2010 at 11:35 UTC
    If you know the index ($ix) of the element you want to move to the first position:
    @array[0..$ix] = @array[$ix, 0..$ix-1]
    Otherwise, and if you are sure the array contains the given element:
    my $element = 'dog'; my $last = $element; for (@array) { ($_, $last) = ($last, $_); last if $last eq $element; }
Re: Putting an elemnt in first position in array.
by johngg (Canon) on Jun 14, 2010 at 14:26 UTC

    Using unshift and splice in a loop will do the trick in this special case as we are not changing the size of the array so the subscript isn't mucked up.

    $ perl -E ' > @arr = qw{ apple ball cat dog elephant fish dog budgie }; > for ( 1 .. $#arr ) > { > unshift @arr, splice @arr, $_, 1 if $arr[ $_ ] eq q{dog}; > } > say for @arr;' dog dog apple ball cat elephant fish budgie $

    I hope this is helpful.

    !-- Node text goes above. Div tags should contain sig only -->

    Cheers,

    JohnGG

Re: Putting an elemnt in first position in array.
by ikegami (Patriarch) on Jun 14, 2010 at 16:11 UTC
    So you want to sort the list such as dog appears first. Well, you could use sort!
    @array = sort { ($a eq 'dog' ? 0 : 1) <=> ($b eq 'dog' ? 0 : 1) } @array;
Re: Putting an elemnt in first position in array.
by Utilitarian (Vicar) on Jun 14, 2010 at 11:12 UTC
    What you want to do is go through the array and if you get a match, put the element on the front of the array, otherwise put it on the end of the array. Reading through marto's links above should make this clear.

    Alternatively you can chose not to learn and use the code below

    print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."
Re: Putting an elemnt in first position in array.
by ahmad (Hermit) on Jun 14, 2010 at 13:19 UTC
    my @array = ("apple","ball","cat","dog","elephant"); unshift @array, 'dog';
    Apparently, This is not what the OP wanted.