Anaximander has asked for the wisdom of the Perl Monks concerning the following question:

how do i delete an element in an array? ex:
@1[1,2,3,4,5,0]; $i=0; if(@1[$i] == 0){ @1[$i] #<delete this print "@1\n"; } else{$i++;} #so that output would be: #(and @1 would be of one less size) #12345

Replies are listed 'Best First'.
Re: simple array question
by bart (Canon) on Feb 04, 2003 at 15:54 UTC
    Use splice or grep.

    If you decide to use splice, either go through the array backwards, or do not increment your index counter when you delete an array item, or you'll skip one in your test.

    grep would be easier:

    @filtered = grep { $_ != 0 } @l;
Re: simple array question
by pfaut (Priest) on Feb 04, 2003 at 15:44 UTC

    You remove elements from arrays with splice. A short excerpt from perldoc -f splice:

    splice ARRAY,OFFSET,LENGTH,LIST
    Removes the elements designated by OFFSET and LENGTH from an array, and replaces them with the elements of LIST, if any.

    push, pop, shift, and unshift can all be expressed as a splice. In your case, you want to delete one entry so specify its index as OFFSET and 1 for LENGTH. You aren't replacing this range with anything so leave off LIST. So splice @1,$i,1 (are you really using numbers for your array names? that sounds kind of odd).

    Also, since in your example you want to remove the last entry from the list, you could use pop.

    --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';
Re: simple array question
by gjb (Vicar) on Feb 04, 2003 at 15:37 UTC

    Have a look at the splice function in the perlfunc documentation page.

    In your case, splice(@1, $#1, 1) will do the trick.

    Hope this helps, -gjb-