Reputation: 193
I know how to delete and splice a value to an array.Currently my code is like this.
my $newDate ="$dayStr/$monthStr/$yearStr";
delete @CONTENTS[9];
splice(@CONTENTS,9,1,$newDate);
This able to the delete and splice in $newDate(DATE)
to the 10th position. However, the problem I met is that the $newDATE(DATE)
not always at the 10th position due to the format of the files set by my users. Luckily, the $newDate(DATE)
is always fixed at 4th position if we count from back.
Any changes solution on how to do this? How to count array from the back so I can get to the 4th position.
My expected result is to delete and splice a value to an array by getting to the 4th position if we count from back.
Thanks for viewing, comments and answers.
Upvotes: 0
Views: 1169
Reputation: 8532
Others have mentioned the use of splice
, but just as a further comment: don't use delete
on array elements. It wasn't supposed to work, and it doesn't work reliably or well-specified. It's only for hashes.
Upvotes: 1
Reputation: 1043
Both of those commands will let you use a negative index to count from the end of the array. Your code is also deleting two elements from your @CONTENTS array. The delete command removes what was in the 9th position and then the splice command removes whatever moved to 9th position, and replaces it with $newDate.
CORRECTION: delete does not remove the array element as pointed out by Miller. It only deletes the value and makes it undef. It is unnecessary though because you are removing the index with the splice command.
Here is your code with negative indexes.
my $newDate ="$dayStr/$monthStr/$yearStr";
delete @CONTENTS[-4];
splice(@CONTENTS,-4,1,$newDate);
Splice: http://perldoc.perl.org/functions/splice.html
Upvotes: 1