Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: compare 2 arrays of strings and form a table

by Roy Johnson (Monsignor)
on Mar 10, 2009 at 18:09 UTC ( #749675=note: print w/replies, xml ) Need Help??


in reply to compare 2 arrays of strings and form a table

You're using numerical comparison (=) rather than string comparison (eq), and your loops aren't very Perlish. You don't describe your problem very clearly, but it looks like you want array2 to indicate values that follow corresponding values from array1: book follows read, apple follows eat, etc.

For the output, the first column should be things that don't appear in array2, and each subsequent column should be the values that follow the values in the previous column. If so, you want to reverse football and tennis in your example.

I found it made the most sense to work with hashes so I could model the "follows" relationship.

#!perl use strict; use warnings; my @array1 = qw(read eat book apple play football novel); my @array2 = qw(book apple novel banana football tennis magazine); # The follows relationship my %follow; @follow{@array1} = @array2; # Keeping track of what followers I have already used my %h2 = map {$_=>1} @array2; # Start with things that are not followers my @out = ([grep !exists $h2{$_}, @array1]); # Put followers of the previous column on as a new column while (%h2) { push @out, [@follow{@{$out[-1]}}]; delete @h2{@{$out[-1]}}; } use Data::Dumper; print Dumper(\@out); END { use Data::Dumper; print Dumper(\@out); }

Caution: Contents may have been coded under pressure.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://749675]
help
Chatterbox?
[1nickt]: Just don't make it barf.
[1nickt]: perldigious that's exactly what my stepson says.
[1nickt]: the tick that can make you a vegetarian
[perldigious]: Your Mother: Yeah, I have a tool for ticks that I use (mostly on my dogs thankfully), but it's just a cheapo one I got from my vets office... it works pretty good though.
erix saw a tick in a natural history museum collected from the scrotum of the curator (it was removed)
[Your Mother]: The exhibit, the tick, or the scrotum?
[erix]: (the man is even a paleontologist )
[1nickt]: erix unfortunately that's there favourite spot. That's why they are usually spotted crawling *up* your leg.
[erix]: ha, the tick and, as it happens, also the curator (now a professor of Paleont.)
[1nickt]: s/there/their/, ugh sorry.

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (12)
As of 2017-05-24 13:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?