Home: Perl Programming Help: Intermediate:
Removing From Array



andy7t
User

Sep 20, 2003, 11:51 AM


Views: 1108
Removing From Array

How you i remove $something for array?

E.G:


if(@array CONTAINS $something)
{
remove (@array, $something);
}

Of course not real perl commands (I think) but i think that should explain what i want. I was thinking of just going @array[NUM] = ""; but i don't know the number- just what the contents is.

I do have this though which does work but is longer:
foreach $array (@arrray)
{

next if $something eq "$array";

push (@newarray, "$array");
}


Is this the sortest way of doing it?


KevinR
Veteran


Sep 20, 2003, 3:40 PM


Views: 1105
Re: [andy7t] Removing From Array

your method should work just fine, its the same as something like this:

for(@ARRAY){
undef $_ if $_ eq $something;
}
-------------------------------------------------


davorg
Thaumaturge / Moderator

Sep 21, 2003, 1:26 AM


Views: 1102
Re: [andy7t] Removing From Array

Your code doesn't remove the element from the array, it sets the element to the empty string. KevinR's sets the element to the value "undef" (almost, but not quite, the same thing).

If you really want to remove the element from the array, then use "grep".


Code
@array = grep { ! (some condition) } @array;


--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks