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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|