Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re: how to rm an element from an array?

by graff (Chancellor)
on Oct 28, 2002 at 01:41 UTC ( [id://208430]=note: print w/replies, xml ) Need Help??

in reply to how to rm an element from an array?

I'd suggest a different call sequence for "yoink()":
yoink( \@arr, $var ); # pass an array ref and a scalar
The sub definition could go something like this, if you don't mind making a copy of the array in order to do the work:
sub yoink { my ($arr_ref, $kill_pattern) = @_; my @out_arr; for (@$arr_ref) { push @out_arr, $_ unless (/^$kill_pattern$/) } @$arr_ref = @out_arr; }
The "yoink" could also use the "splice" function (see perldoc -f splice) to edit the array in place; I suspect the "optimal" choice would depend on array size and number of elements being removed -- with big arrays, doing just a few edits will go best with splice, but doing lots of edits might go quicker using selective copying to a separate array. (For small arrays, there won't be a noticeable difference.)

update: IO's solution is better than mine, of course. (I just forgot that I should've known better...)

Replies are listed 'Best First'.
Re^2: how to rm an element from an array?
by atcroft (Abbot) on Oct 28, 2002 at 03:12 UTC

    Why not a combination of the two solutions, something like:

    sub yoink { my ($array_ref, @kill_patterns) = @_; foreach my $kp (@kill_patterns) { @{$array_ref} = grep $_ ne $kp, @{$array_ref}; } }
    That way, you could call it with one or more kill patterns, such as &yoink(\@arr, $kp), or &yoink(\@arr, $kp1, $kp2, $kp3), or so forth... (At least, I think it would work....)
      If you always want to modify the original array, you could use function prototypes (let the scolding begin!) and use yoink like a builtin. That way, you wouldn't have to keep passing \@arr as a ref like that. However, if you want to keep the original array intact and let yoink return a separate copy with the proper yoinkage, then this is certainly not at all what you want.
      sub yoink(\@$) { my ($array_ref, $remove) = @_; @$array_ref = grep { $_ ne $remove } @$array_ref; } my @arr = qw/un deux trois quatre cinq six sept huit/; # no passing of \@arr -- oh, so pretty! yoink @arr, 'deux'; print "@arr\n"; __END__ un trois quatre cinq six sept huit


        Slightly different, but I quite like this:

        sub yoink (&\@) { @{$_[1]} = grep !$_[0]->($_), @{$_[1]} } my @arr = qw( aa bb cc ); yoink { $_ eq 'bb' } @arr; print "@arr\n";

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://208430]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (2)
As of 2024-05-28 23:54 GMT
Find Nodes?
    Voting Booth?

    No recent polls found