I want to rearrange array elements based on user input.
foreach $element (@array)
{if ($element == $input) # if $input exist in @array
{move $element to first postition and rearrange remaining}
else # if $input does not exist in @array
{unshift @array, $input;}}
Understand? It should work similar to the "recent post" on this site.
[perl]
$counter=0;
foreach $element (@array) {
if ($element == $input) { # check if this element matches the input
splice @array,$counter,1; # if so, remove it...
unshift @array, $input; # ...and put it to the front
$flag=1; # set a flag so we know we've found a match
}
$counter++; # increment the counter
}
# next check if we've found a match, if not add the input to the start of @array
unless ($flag) {
unshift @array, $input;
}
[/perl]
Hopefully that'll get you up and running, although it's untested code...
Something like this should be more efficient, using 'last' to break out of the loop once a match is found:
[perl]
for ($i=0; $i < $#array; $i++) {
if ($array[$i] == $input) {
splice @array,$i,1; # remove element if a match found
last;
}
}
unshift @array, $input; # add $input to the start of the array
[/perl]