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

use strict; use warnings; my %assocs; while (<DATA>) { my ($k, $v) = split; $assocs{$k} = $v; } my %roots; $roots{$_} = 1 for keys %assocs; $roots{$_} = 0 for values %assocs; my @chains; for my $root (grep $roots{$_}, keys %roots) { my $node = $root; my @chain; while (defined($node)) { push @chain, $node; $node = $assocs{$node}; } push @chains, \@chain; } { local $\ = "\n"; local $, = "\t"; print @$_ for @chains; } __DATA__ read book eat apple book novel apple banana play football tennis football novel mazagine
eat apple banana play football read book novel mazagine tennis football

Oops, the output is different than what you asked for. Did I misunderstand the question?

Replies are listed 'Best First'.
Re^2: compare 2 arrays of strings and form a table
by ikegami (Patriarch) on Mar 10, 2009 at 18:37 UTC
    Ok, this one actually gives the output you asked by ignoring order.
    use strict; use warnings; my %sets; my %owner; while (<DATA>) { my ($p, $q) = sort split; next if $p eq $q; $sets{ $owner{$p} ||= $p }{$p} = 1; $sets{ $owner{$q} ||= $q }{$q} = 1; %{ $sets{$p} } = ( %{ delete( $sets{ $owner{$p} } ) }, %{ delete( $sets{ $owner{$q} } ) }, ); $owner{$p} = $p; $owner{$q} = $p; } { local $\ = "\n"; local $, = "\t"; print(keys(%$_)) for values(%sets); } __DATA__ read book eat apple book novel apple banana play football tennis football novel mazagine
    eat banana apple read book mazagine novel tennis play football