in reply to Array comparison for 3 arrays
Telling us where you got stuck may help.
I see for a start that you seem to be trying to use variable names (for the arrays) that include spaces. Perl doesn't let you do that and will tell you off for it (although the error message may not be entirely clear).
If you want to deal with several 'things' you have a few choices. You could use a separate variable for each (your current approach), but that quickly becomes hard to manage, or you can use an array or a hash to organise the 'things'. If you want to deal with them by name a hash is the right beastie otherwise an array may be more appropriate.
By the look of your current code it seems you probably want to deal with the arrays by name so a hash is the appropriate variable to manage your collection of 'things' (arrays). Consider:
#!/usr/bin/perl use strict; use warnings; use List::Util; # Read the lists of numbers my %lists; my $nameWidth = 5; my $maxNum = 0; # Implicit assumption that minimum value is 0 while (<DATA>) { next if ! /^([^=]+)\ =\s* {([^}]+)/x; my ($name, $list) = ($1, $2); my @values = split /\s*,\s*/, $list; $name =~ s/^\s+|\s+$//g; # Trim leading and trailing white space $lists{$name} = {map {$_ => 1} @values}; $nameWidth = length ($name) + 1 if $nameWidth <= length $name; $maxNum = List::Util::max ($maxNum, @values); } my @names = sort keys %lists; my $template = "-%4s " . ("%-${nameWidth}s" x @names) . "\n"; printf $template, '', @names; for my $row (0 .. $maxNum) { my @values; for my $name (@names) { my $list = $lists{$name}; push @values, exists $list->{$row} ? 'yes' : ''; } printf $template, $row, @values; } __DATA__ Array 1 = {0, 1,2,3,4,5,6,7,8,9} Array 2 = {1,2,3,4,6,8, 10, 12,14} Array 3 = {1,2,3,5,7,9, 11,13,15}
Prints:
Array 1 Array 2 Array 3 0 yes 1 yes yes yes 2 yes yes yes 3 yes yes yes 4 yes yes 5 yes yes 6 yes yes 7 yes yes 8 yes yes 9 yes yes 10 yes 11 yes 12 yes 13 yes 14 yes 15 yes
There is quite a lot going on in there so you are going to need to study the code for a while and consult the Perl documentation. You may even need to come back and ask some more questions, but try to figure it out for yourself for a start and do read the documentation!
|
|---|