#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2008
    Posts
    56
    Rep Power
    7

    Remove entries in an array, and work out the new structure?


    If I have an array as below:

    $array[0] = "entry 0";
    $array[1] = "entry 1";
    $array[2] = "entry 2";
    $array[3] = "entry 3";
    $array[4] = "entry 4";
    $array[5] = "entry 5";

    If I remove (say) the element number 1 and 4, all elements will move places downwards, number 5 moving down twice.

    Is there away to create an associative array so I could grab the value of (say) $oldarray{'2'} and the value would be the new position of old $array[2] (so $array[1], the value of the associative array being '1')?

    I need to do this to update a seperate array of data when an array changes.

    Thanks.
  2. #2
  3. wizard
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2009
    Location
    The Great White North
    Posts
    79
    Rep Power
    138
    Originally Posted by Lectrician
    If I have an array as below:

    $array[0] = "entry 0";
    $array[1] = "entry 1";
    $array[2] = "entry 2";
    $array[3] = "entry 3";
    $array[4] = "entry 4";
    $array[5] = "entry 5";

    If I remove (say) the element number 1 and 4, all elements will move places downwards, number 5 moving down twice.
    How do you remove the values? Code please.

    Originally Posted by Lectrician
    Is there away to create an associative array so I could grab the value of (say) $oldarray{'2'} and the value would be the new position of old $array[2] (so $array[1], the value of the associative array being '1')?

    I need to do this to update a seperate array of data when an array changes.

    Thanks.
    This sounds like you're using the wrong data structure(s) for the job. What are you trying to do?
    __END__

    I love Perl; it's the only language where you can bless your thingy.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    828
    Rep Power
    496
    Are you sure you really need to remove array elements? It might be easier to just set the elements to an empty string or to undef them:
    Perl Code:
    undef $array[1];
    undef $array[4];

    Now, your array looks like this:
    Code:
    0  'entry 0'
    1  undef
    2  'entry 2'
    3  'entry 3'
    4  undef
    5  'entry 5'

IMN logo majestic logo threadwatch logo seochat tools logo