-
Notifications
You must be signed in to change notification settings - Fork 315
/
ch-2.pl
73 lines (61 loc) · 1.98 KB
/
ch-2.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/perl
# https://perlweeklychallenge.org/blog/perl-weekly-challenge-032/
# Task #2
# ASCII bar chart
# Write a function that takes a hashref where the keys are labels
# and the values are integer or floating point values.
# Generate a bar graph of the data and display it to stdout.
# The input could be something like:
#
# $data = { apple => 3, cherry => 2, banana => 1 };
# generate_bar_graph($data);
# And would then generate something like this:
#
# apple | ############
# cherry | ########
# banana | ####
# If you fancy then please try this as well:
# (a) the function could let you specify whether the chart
# should be ordered by (1) the labels, or (2) the values.
use strict;
use warnings;
use List::Util qw/max/;
my $source = { apple => 3, cherry => 2, banana => 1, orange => 2.5 };
print "Sorted by name\n";
generate_bar_graph($source,{sort => 'labels' });
print "Sorted by value\n";
generate_bar_graph($source,{sort => 'values' });
sub generate_bar_graph {
my $data = shift;
my $args = shift;
my @sorted_keys = keys %$data;
if ($args->{sort} eq 'values') {
# keys sorted by values (desc)
@sorted_keys = reverse sort { $data->{$a} <=> $data->{$b} } @sorted_keys;
}
else{
# keys sorted (asc)
@sorted_keys = sort @sorted_keys;
}
my $inc = 50 / max (values %$data); # percentage increment
print join "\n",
map { sprintf '%-10s| %s',
$_,
'#' x ($data->{$_} * $inc)
}
@sorted_keys;
print "\n";
return;
}
__END__
./ch-2.pl
Sorted by name
apple | ##################################################
banana | ################
cherry | #################################
orange | #########################################
Sorted by value
apple | ##################################################
orange | #########################################
cherry | #################################
banana | ################