Deleting array element does not change the array size.

Discussion in 'Perl Misc' started by Sean Nakasone, Oct 23, 2007.

  1. 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??
     
    Sean Nakasone, Oct 23, 2007
    #1
    1. Advertising

  2. Sean Nakasone

    Guest

    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.
     
    , Oct 23, 2007
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Harry Barker
    Replies:
    2
    Views:
    547
    Alf P. Steinbach
    Apr 19, 2006
  2. Umesh

    Deleting Array Element

    Umesh, Jun 13, 2007, in forum: C Programming
    Replies:
    13
    Views:
    512
    John Bode
    Jun 14, 2007
  3. HANM
    Replies:
    2
    Views:
    767
    Joseph Kesselman
    Jan 29, 2008
  4. justineee

    Deleting an element in an array..

    justineee, Oct 26, 2008, in forum: Java
    Replies:
    3
    Views:
    4,049
    Roedy Green
    Oct 27, 2008
  5. crea
    Replies:
    2
    Views:
    444
    Nobody
    Dec 28, 2012
Loading...

Share This Page