On 25 Jul 2006,
wrote:
> Forgive me if I am limited to some degree. I am just asking if someone
> can provide some sample code that works takes $multidimarray[1][0],
> $multidimarray[2][0], (a column) and produces a distinct count...
>
> I dont know how to take your suggestion of
> map { $_->[0] } @columnarray
> and convert that into a solution for that counts the distinct entires
> for the first column in a multidimensional array ..
I'll try to help you. Keep in mind that the advice Paul gave was
useful, I'm just restating it and elaborating. Don't feel bad about
missing things here and there, everyone has to start somewhere.
That map call will return the first (0) column of the array as a list.
Your original question was how to find unique elements in a column.
You posted:
> sort @$columnarray;
> @out = grep($_ ne $prev && ($prev = $_, 1), @$columnarray);
> if ($#out == -1) { $#out = 0; }
> $out = $#out +1; # makes $#out of 0 = 1 so it gets counted !
> push @distinctcounts, $out;
The first line does nothing at all. Paul mentioned that too. Use
warnings and strict mode, if possible, to avoid such code. Sort
*returns* the sorted list, it doesn't modify in place.
In addition your 'uniques' code is not very good. It may work in some
cases, but really you should use a hash. Look at 'perldoc -q
duplicates' and 'perldoc perldata' to get started. Actually all of
the perldoc info is good
Here's a (very simple) function to give you the unique items from a
list you pass:
sub uniques
{
my %unique = ();
$unique{$_}++ foreach @_;
return keys %unique;
}
Now use it like this:
my @columnarray = ( [1,2,3], [1,2,3], [4,5,6], [7,8,9], );
foreach my $column (1 .. scalar @{$columnarray[0]})
{
print "Unique elements in column $column: ";
print join ', ',
uniques(map { $_->[$column-1] }
@columnarray
);
print "\n";
}
I formatted this to be easy to understand, and I tested it with the
data above under
use warnings;
use strict;
and it worked correctly. Please learn from the code posted above - it
shows many useful techniques.
Ted