Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Remove array element by value

Status
Not open for further replies.

rob51383

Programmer
Jun 23, 2004
134
US
Is it possible to remove an array element by its actual value. For instance:

$input_Color=Green;
@array=(Red,Blue,Green,Yellow,Black);
splice(@array,$input_Color);

The problem is I do not know the value of $input_Color, and I would not know the index of which element to remove without creating a bunch of IF statements or cycling it through a loop (Which I am currently doing)
 
One way:

Code:
my $input_Color = 'Green';
my @array = qw(Red Blue Green Yellow Black);
@array = grep {!/$input_Color/} @array;
print "@array";
 
another way without using a regexp:

Code:
my $input_Color = 'Green';
my @array = qw(Red Blue Green Yellow Black);
@array = grep {$_ ne $input_Color} @array;
print "@array";
 
I'd go with the second way.
Code:
@array = grep {$_ ne $input_Color} @array;
The first way using a regex as given tries to match $input_color anywhere in each of the elements of @array. So, for example, if @array looks like this:
Code:
my @array = qw(Red Blue [b]Green Greenish-Blue Bluish-Green[/b] Yellow Black);
the regex method would eliminate Greenish-Blue and Bluish-Green from the array along with Green.

To make the regex method work as I think you intend, you'd have to use anchors, and say
Code:
@array = grep {!/[b]^[/b]$input_Color[b]$[/b]/} @array;
which will force the regex to match each element in its entirety, rather than matching anywhere within each element.

Why bother with that, though? {$_ ne $input_color} is better.




 
Any particular reason you couldn't go with a hash instead of an array? If order matters, it would take some doing to get it working right. For small lists, like the examples, it wouldn't make much of a difference and probably wouldn't be worth the effort.

But if you're playing with a large list, every time you want to remove an item by using grep, it iterates through every member of the array. A hash might not work for your situation, but it would make deleting individual members a bit easier because you can directly address the members..

Just a thought.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top