[comp.lang.perl] Table inversion

merlyn@iwarp.intel.com (Randal Schwartz) (12/02/90)

In article <EMV.90Nov30194551@poe.aa.ox.com>, emv@ox (Ed Vielmetti) writes:
| A nice example of how to load data into an associative array with some
| kind of <<ENDOFTABLE construct would be welcomed (if it's not already
| in there).  Or several associative arrays, for that matter.  I'd like
| to have some way of taking a table
| 
| news/readers	rn,nn,trn
| news/nntp	nntp,nntpxmit,nntplink
| gnu		binutils,flex,fileutils
| x11/games	xtrek
| lwall		rn,patch,perl
| ENDOFTABLE
| 
| and turning it into
| 
| $category{"rn"} -> "news/readers,lwall"
| $category{"nntpxmit"} -> "news/nntp"
| $category{"binutils"} -> "gnu"

for (split(/\n/,<<ENDOFTABLE)) {
news/readers	rn,nn,trn
news/nntp	nntp,nntpxmit,nntplink
gnu		binutils,flex,fileutils
x11/games	xtrek
lwall		rn,patch,perl
ENDOFTABLE
	($key,$rest) = split;
	for (split(/,/,$rest)) {
		if (defined($category{$_})) {
			$category{$_} .= ",$key";
		} else {
			$category{$_} = $key;
		}
	}
}

for (sort keys category) {
	print "$_\t$category{$_}\n";
}

print "Just another Perl hacker,"
-- 
/=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\
| on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III      |
| merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn |
\=Cute Quote: "Intel: putting the 'backward' in 'backward compatible'..."====/