in reply to Tabular Data, Group By Functions

The following should be self-explanatory. Ask if you have questions.

use strict; use warnings; my @data; <DATA>; # Skip header. while (<DATA>) { chomp; push(@data, [ map { 0+$_ } split(/\t/, $_) ]); } # Sort by "In". my @in_sorted = sort { $a->[1] <=> $b->[1] } @data; # Sort by "Out". my @out_sorted = sort { $a->[2] <=> $b->[2] } @data; # Sum "In" and "Out" by "Day". my %in_day; my %out_day; foreach (@data) { my $day = $_->[3]; # Avoid warnings. $in_day{$day} ||= 0; $out_day{$day} ||= 0; $in_day{$day} += $_->[1]; # "In" $out_day{$day} += $_->[2]; # "Out" } __DATA__ ID In Out Day 1 5 2 1 2 4 9 2 3 3 3 2 4 6 7 3 5 5 0 5 6 7 9 3 7 8 9 4 8 6 6 4

Replies are listed 'Best First'.
Re^2: Tabular Data, Group By Functions
by monkfan (Curate) on Jun 14, 2005 at 14:48 UTC
    Hi ikegami,

    Genial!
    What's the meaning of '0+$_' in :
    push(@data, [ map { 0+$_ } split(/\t/, $_) ]);
    ???
    Regards,
    Edward

      Are you asking what $_ is? Or what the idiom 0 + $variable is?

      $_ is the current topic. It's the single item that gets passed to map every time through

      0 + $variable (where your variable is $_) takes a string that contains a number, (like "7") and changes it into an actual number, (like 7). Basically, adding 0 "numifies" the string.

          -Bryan

      Up until that point, the data exists as strings internally. That forces the data to be converted to numbers internally. I did that to pretty up the Data::Dumper output.