Im programming in Perl, can I replace an element in an array with two new elements?

January 21, 2012 – 5:22 pm

For example, if I had the array @values=(1,2,3,4) is it possible that I replace the 2nd element with two new elements of 5 and 6; so @values would now equal (1,5,6,3,4)? And I don’t care which number element the 5 and 6 take.

Related posts:

  1. one to many elements in an array in perl?
  2. Deleting a specific Element from a Perl Array?
  3. I want to perform a calculation in Perl that should be done with every element in an array. Help?
  4. I want to perform a calculation in Perl that should be done with every element in an array. Help?
  5. How can i sum all elements of an array in perl?
  6. In Perl, how do I add elements of an array using a loop?
  7. In Perl, how do I add elements of an array using a loop?
  8. How do I Compare 2D Array Elements in Python?
  9. Simple Perl array/for loop question…?
  10. simple way to see if an element exists in a ruby array?
  1. One Response to “Im programming in Perl, can I replace an element in an array with two new elements?”

  2. splice @values, 1, 1, 5, 6;

    The arguments to splice are:
    array – the array to operate on
    offset – the offset at which to start removing elements (1 = second element)
    length – the number of elements to remove
    list – replacement elements (5, 6)

    This program:
    ===================
    #!/usr/bin/perl
    @values = (1, 2, 3, 4);
    splice @values, 1, 1, 5, 6;
    print @values, "\n";
    ===================

    … prints:
    ===================
    15634
    ===================

    That’s what you want, right?

    @M

    By McFate on Jan 21, 2012

Sorry, comments for this entry are closed at this time.