Skip to content

Instantly share code, notes, and snippets.

@ggl
Last active September 10, 2016 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggl/81520610c52374fdc68ce5b350ed307a to your computer and use it in GitHub Desktop.
Save ggl/81520610c52374fdc68ce5b350ed307a to your computer and use it in GitHub Desktop.
Generate a histogram from a list of numbers
#!/usr/bin/end perl
use strict;
use warnings;
use Data::Dumper;
my $hist = sub {
my $input = shift;
if ($input and $input =~ /^\d+$/) {
my ($i, $j) = (1, 10);
while ($j <= 1e9) {
if ($input >= $i and $input < $j) {
return $j;
}
else {
$i *= 10;
$j *= 10;
}
}
return 1e9;
}
else {
return 'junk';
};
};
unless ($ARGV[0]) {
print "usage: $0 <samples_file>\n";
exit 0;
}
elsif (-f $ARGV[0]) {
open(my $fh , '<', $ARGV[0]) or die "Unable to open file $ARGV[0]: $!";
my %hg;
while (<$fh>) {
chomp;
my $res = $hist->($_);
print "$res\n";
if ($hg{$res}) {
$hg{$res}++;
}
else {
$hg{$res} = 1;
}
}
close $fh;
print Dumper \%hg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment