CDN
CDN

Reputation: 167

Modifying Array Contents using Splice

I'm trying to work on a script which inserts a '1' at a particular array location using splice function, prints it and later inserts a '0' at the same location. The logic i have so far is :

my @array = (0) x 4096;
for ($j=0;$j<3;$j++) {
splice ( @array, $array[$j],1,1);
print "$j---$array[$j]\n";
splice ( @array, $array[$j],1,0 );
}

With this logic, the output I'm getting is : 0---1 1---0 2---0

To be more precise, the output I was expecting out of this logic is : 0---1 1---1 2---1

Am I using the splice function correctly here ?

Upvotes: 1

Views: 115

Answers (2)

perreal
perreal

Reputation: 98078

splice wants an index not an element:

splice ( @array, $j,1,1);

in your case you are passing 0 (the element value) as the index so it inserts an element at the beginning. But replacing a single element with a single element is better done with simple assignment.

Upvotes: 1

toolic
toolic

Reputation: 62163

I don't think you need splice to do what you want. Just a simple assignment is needed:

use warnings;
use strict;

my @array = (0) x 4096;
for (my $j = 0 ; $j < 3 ; $j++ ) {
    $array[$j] = 1;
    print "$j---$array[$j]\n";
    $array[$j] = 0;
}

__END__

0---1
1---1
2---1

Refer to:

perldoc -f splice

Upvotes: 1

Related Questions