How to compare two lists (arrays) in perl
I've got two lists (1 & 2). All I need to do is remove elements from list 1 if that element is listed in list 2. Here's how I'm doing it now, but I feel it's the hard way.
Code:
for(my $i=0; $i<=$#list1; $i++){ I know I'll feel dumb once I see how to do it better. Thanks PS: I'm consciously using 'delete' instead of 'splice' because I need the elements in list1 to maintain their positions. |
If you want to use the same criteria as above (case-insensitive, fixed-string matches), then the method above is essentially how I would go about doing it (although I might write it with two foreach-style loops).
If, however, you want to test for exact equality of strings (not matches, and not case-insensitive), you can use the uniqueness property of hashes. E.g., Code:
#!/usr/bin/perl -w |
work that one out!
Code:
Code:
[billy@daffy lxq]$ ./1.pl unreadable! |
Quote:
Code:
@C=grep!${{map{$_,1}@B}}{$_},@A; Code:
@C=map{!${{map{$_,1}@B}}{$_}&&$_||undef}@A; Code:
${{map{$_,1}@B}}{$_}&&undef$_ for@A; |
See also List::Compare, which does set unions and complements (where set complement is the same thing as set difference). Unfortunately, it does not preserve indices.
|
Thanks for all the answers. The map command you gave me (below) works awesome. Now if I could only understand it.
Code:
@C=map{!${{map{$_,1}@B}}{$_}&&$_||undef}@A; Code:
map{$_,1}@B I understand the following part returns the element from @A if true, else returns undef. Code:
&&$_||undef Code:
!${{map{$_,1}@B}}{$_} Maybe I'll get it if I keep working with it, but a little help would be nice. |
Apologies all: Post removed since I realized I don't see it at all. Anyone care to enlighten us?
|
Quote:
Quote:
Code:
%hash = (1, 2, 3, 4); Code:
%hash1 = (map{$_,1} @B); Code:
%hash = (map{$_,1} @B); Code:
%hash1 = (map{$_,1} @B); Code:
%seen = (); |
Quote:
Quote:
anyway, i think we can agree that this is an exercise in unreadable code but interesting in a programming exercise context. I think the OP's original is much better as regards keeping it simple. |
well windowbreaker,
if you find this style interesting intellectually, you should have a go at LISP or maybe Haskell. they are especially good at this sort of lateral thinking. |
LISP ????... LISP ????. Shouldn't that be reducable to one line in lisp ???.
Haven't seen (as in used) that since (early) Uni days. And that was a while ago - images of PDP's wander past ... Write a syntax parser in lisp ... foggy/drunken undergrad days evoked. Billy, don't do that to a fella. |
Hi.
If one uses perl a lot, the item below may be useful. Chapter 4 deals with arrays, and recipes are provided for simple and symmetric differences of arrays. The first edition can be obtained used for less than $10 ... cheers, makyo Code:
Title: Perl Cookbook |
Quote:
Quote:
|
doh
we all have off days. |
All times are GMT -5. The time now is 10:47 PM. |