In a message dated 2/26/2004 6:04:59 PM Eastern Standard Time, 
[EMAIL PROTECTED] writes:
>Is there a command to drop an element from an array, or what is the best
>way to do this.
>
>Any help appreciated.

Look into splice. delete doesn't remove elements as you may expect, 
just...deletes them. 
splice ARRAY; OFFSET LENGTH REPLACE

I always just use this, because I hate removing elements and worrying about 
it:

use strict;
use warnings;
sub remove_el (\@@) {
    my $array = shift;
    my @el_rem;
    for (sort {$b <=> $a} @_) {
        if (! exists $array->[$_]) {
            warn 'element ', $_, ' does not exist';
            next;
        }
        push @el_rem, splice(@$array, $_, 1);
    }
    return @el_rem;
};

my @sample = ('a', 'b', 'c', 'd', 'e', 'f', 'g');
remove_el @sample, 6, 2, 4, 1;

If you just need to remove 1 element a time or a length of elements, you 
should just use splice. But sometimes when you have to remove different elements 
in no particular order at no particular time, it gets annoying. Especially if 
you are doing something and you have to remove element 3 and 8 at the same 
time, and if you remove 3 first, element 8 will be different. We have subroutines 
to make considering this stuff more than once minimal. 


-Will
-----------------------------------
Handy Yet Cryptic Code. 
Just to Look Cool to Look at and try to decipher without running it.

Windows
perl -e "printf qq.%3i\x20\x3d\x20\x27%c\x27\x09.,$_,$_ for 0x20..0x7e"

Unix
perl -e 'printf qq.%3i\x20\x3d\x20\x27%c\x27%7c.,$_,$_,0x20 for 0x20..0x7e'

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to