Perl - How do we delete and splice value to an array?

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

Answers (3)

LeoNerd
LeoNerd

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

Victor Bruno
Victor Bruno

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

Miller
Miller

Reputation: 35208

splice allows a negative offset that starts from the end of the array:

my @array = (1..10);
splice @array, -4, 1, ('foo');
print join(',', @array), "\n";

Outputs:

1,2,3,4,5,6,foo,8,9,10

Upvotes: 3

Related Questions