Deleting array element does not change the array size.

S

Sean Nakasone

Below I have a simple script that will build an array then delete an
element from it. After deleting the element, the size of the array still
remains the same. I'm a perl newbie and would like to know the correct
way to delete an array element and to obtain the new array size.

use strict;
use warnings;

my @arr = (1, 2, 3);
print @arr; # outputs "123"
my $size = @arr;
print "\nsize=$size\n";
delete $arr[1];
print @arr; # outputs "13"
$size = @arr;
print "\nsize=$size\n"; # this is still 3, why??
 
X

xhoster

Sean Nakasone said:
Below I have a simple script that will build an array then delete an
element from it. After deleting the element, the size of the array still
remains the same. I'm a perl newbie and would like to know the correct
way to delete an array element and to obtain the new array size.

from perldoc -f delete:

Note
that deleting array elements in the middle of an
array will not shift the index of the ones after
them down--use splice() for that.

So, you would use splice for that.

use strict;
use warnings;

my @arr = (1, 2, 3);
print @arr; # outputs "123"
my $size = @arr;
print "\nsize=$size\n";
delete $arr[1];

splice @arr, 1, 1;

Xho

--
-------------------- http://NewsReader.Com/ --------------------
The costs of publication of this article were defrayed in part by the
payment of page charges. This article must therefore be hereby marked
advertisement in accordance with 18 U.S.C. Section 1734 solely to indicate
this fact.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top