Re: how to implement this with perl



vikingy wrote:
Hi all,

Hello,

I have two files,one is label file,another is thickness file, they are one to one correspondence, for example:
the label file is : 2 2 3 2 1 3 4 5 2 5 1 4 ......
the thickness file is: 0.3 0.8 0.2 0.1 2.4 0.9 3.2 0.2 0.1 0.3 2.1 2.3 ......
Now I want to calculate the sum and mean thickness of the same labeled, just like this:
label 1 : 2.4
label 2 : (0.3+0.8+0.1 +0.1)/4
label 3 : (0.2+2.4)/2
label 4 : (3.2+2.3)/2
label 5 : (0.2+0.3)/2
.......
and then there is also a index [3 4] to select the label, so in the end ,I want to get the sum and mean of (0.2+2.4)/2, (3.2+2.3)/2.

I'm a beginner to perl, and don't know how to implement this with perl,could you give me some suggestion? thanks in advance!

This is one way to do it:

#!/usr/bin/perl
use warnings;
use strict;

use List::Util qw/ sum /;

open my $L, '<', 'label' or die "Cannot open 'label' $!";
my @labels = split ' ', <$L>;
close $L;

my %data;
for my $index ( 0 .. $#labels ) {
push @{ $data{ $labels[ $index ] } }, $index;
}

open my $T, '<', 'thickness' or die "Cannot open 'thickness' $!";
my @thicknesses = split ' ', <$T>;
close $T;

for my $label ( keys %data ) {
for my $index ( @{ $data{ $label } } ) {
$index = $thicknesses[ $index ];
}
}

for my $label ( sort { $a <=> $b } keys %data ) {
my $sum = sum @{ $data{ $label } };
my $mean = $sum / @{ $data{ $label } };
print "label $label sum: $sum mean: $mean\n";
}

__END__



John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
.



Relevant Pages

  • Re: Coming from Perl
    ... characters inside that string. ... In this case 'EndHTML' is a label, and I'm telling perl to print everything as is up to that label. ... "Others make web sites. ...
    (comp.lang.python)
  • Re: [OT] Re: nesting coments
    ... > By using a consistent naming convention for the label names (as suggested ... > and the ones used for commenting out ... > large blocks of Perl code. ...
    (comp.lang.c)
  • Re: Perl 5.00404 - Label not found for "next " , next() function
    ... Do I have any environment variables set before I run perl? ... J. Gleixner wrote: ... Label not found for "next " ...
    (comp.lang.perl.misc)
  • Re: How to write a nested if-statement
    ... Firstly hould be in lowercase. ... Secondly there is no in perl or ... What is LOOP? ... If it is a label it should be writen as: ...
    (perl.beginners)
  • Re: Use a label in a FooterTemplate control? Surely, there must be a way...
    ... If Visual Studio didn't add your Label to this list for you, ... Something else I want to point out to you is that your quotes are mismatched ... simply SUM up the $$ amounts from all the records in the repeater. ... So I tried to place a Label control in the footer and fill the Text of the ...
    (microsoft.public.dotnet.framework.aspnet)