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

Dear Monks

Is it possible to insert an element into an array at say position 5, so that the element at position 5 is not overwritten but shunted to position 6 and hence all later elements in the array are shunted along by one position too. This way we do not overwrite the element when we insert a new value at the specified position but make the array size bigger by one

thanks a lot
  • Comment on insert element into array so that don't overwrite data at that position?

Replies are listed 'Best First'.
Re: insert element into array so that don't overwrite data at that position?
by wind (Priest) on Apr 29, 2011 at 23:08 UTC

    use splice

    my @array = (0..7); splice @array, 4, 0, ('inserted-array'); print "@array\n";

    Note: the other array operators (push, pop, shift, and unshift) can all be done with splice as well:

    # push @array, @others; splice @array, @array, 0, @others; # my $element = pop @array my $element = splice @array, $#array, 1; # my $element = shift @array my $element = splice @array, 0, 1; # unshift @array, @others splice @array, 0, 0, @others;

    Update: Fixed slight bug in push and pop equivalents. Ty AnomalousMonk