in reply to Re^2: how to sum over rows based on column headings in perl
in thread how to sum over rows based on column headings in perl

#!/usr/bin/perl use strict; use warnings; use autodie; if (@ARGV != 1){ print "USAGE: ./parse-counts.pl file\n"; exit(1); } my $mutfile = $ARGV[0]; open(INPUTR,"<$mutfile") or die "Can't open \$mutfile for reading. \n" +; my (%counts, %unique, %masks); my ($headname, @unique) = grep !$unique{$_}++, my @headers = split ' ' +, <INPUTR>; for my $label ( @unique ) { $masks{$label} = join ' ', map { $_ eq $label ? 'M' : '_' } @headers[1..$#headers]; } my $line; while($line=<INPUTR>) #while(<DATA>) { chomp $line; $line =~ s/\s+/ /g; # for uniform spacing my ($name, $letters) = split ' ', $line, 2; $counts{$name}{$_} += ($masks{$_} | $letters) =~ /M/ for @unique; } print "$headname @unique\n"; print "$_ @{ $counts{$_} }{@unique}\n" for sort keys %counts;

Replies are listed 'Best First'.
Re^4: how to sum over rows based on column headings in perl
by angerusso (Novice) on Jul 31, 2015 at 18:48 UTC

    Thanks so much! It works beautifully and I understand it much better now. am also glad I learnt "map" function today. Also learnt how to use a 3rd parameter in the split function. Hoping to use them again for a new codes I plan to write in future. Will practice!