Deleting array element does not change the array size.

Deleting array element does not change the array size.

am 23.10.2007 03:39:27 von seannakasone

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??

Re: Deleting array element does not change the array size.

am 23.10.2007 03:44:00 von xhoster

Sean Nakasone wrote:
> 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.

Re: Deleting array element does not change the array size.

am 23.10.2007 03:52:18 von Petr Vileta

Sean Nakasone wrote:
> 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??

splice is the right keyword :-)

use strict;
use warnings;
my @arr = (1, 2, 3);
print @arr; # outputs "123"
my $size = @arr;
print "\nsize=$size\n";
#######################
splice @arr,1,1;
#######################
print @arr; # outputs "13"
$size = @arr;
# line above could be: $size = $#arr;
print "\nsize=$size\n"; # this is still 3, why??

--

Petr Vileta, Czech republic
(My server rejects all messages from Yahoo and Hotmail. Send me your mail
from another non-spammer site please.)