Sumit am Montag, 9. Juli 2007 09:43:
> Hey Guys,

Hi Sumit

> I am a new bie to this Group.
> I have a Problem.
> I want to remove an element from an array whose index i dont know.
>-----------------------
>
> #!/usr/bin/perl -w
> use strict;

use warnings; # additionaly

> my @updateNames = ();
> my @tempArr = ();
> my $item = "";
> my $item2 = "";
>
> push @updateNames,"I_love_you";
> push @updateNames,"I_love_you_too";
> push @updateNames,"I_hate_you";
>
> push @tempArr,"I_love_you";
> push @tempArr,"I_love_Him";
> push @tempArr,"I_hate_you";


# This can be shortened, avoiding all the pushs:

my @updateNames = qw( I_love_you I_love_you_too I_hate_you );
my @tempArr     = qw( I_love_you I_love_Him I_hate_you );

# my ($item1, $item2); ==> better declared locally in the  loops below


> foreach $item (@updateNames)

foreach my $item (@updateNames) # etc.

> {
>     foreach $item2 (@tempArr)
>     {
>         if ($item eq $item2)
>         {
>             pop @updateNames,$item;  #This pop is just removing the
> last element i want to remove $item2 from @updateNames
>         }
>     }
> }

# You want to remove all elements from @updateNames that are contained
# in @tempArr. To avoid a lot of array traversing,
# it's better to use a hash as indexing data structure.
# I use the grep function to extract only the wanted elements out of 
# @updateNames.
#
# The above nested loops would then be replaced by:

my %index = { map $_ => 1 } @tempArr;

@updateNames = grep !exists $index{$_}, @updateNames; # see perldoc -f grep

> print "\n";
> foreach $item (@updateNames)
> {
>     print $item;
>     print "\n";
> }

print $_, "\n" for @updateNames;



Dani

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


Reply via email to