in reply to Failed array attemp
I have two arrays and if an element in 1st array is in 2nd array I want to append "+" to array 3. If it's not I want to append '-' to array 3.
Just doing exactly what you say you want (and using numeric comparison because you did) would give:
If your arrays stay short, this method might be fine, but you might want to avoid iterating over @y for each and every element of @z. A better way to do it would be:for my $x (@x) { push @z, (grep {$_ == $x} @y) ? '+' : '-'; }
And if this is something you are doing a lot, you should just wrap it up in a sub so you can call it with references to two arrays and get a reference to a newly constructed array in return.my %k = map {($_, 1)} @y; for my $x (@x) { push @z2, (exists $k{$x}) ? '+' : '-'; }
Don't worry about having short code. My second example is a little longer but still more efficient. You should focus on writing good and readable code and then reusing it properly.
|
|---|