aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2019-10-28 16:54:35 +0000
committerGitHub <noreply@github.com>2019-10-28 16:54:35 +0000
commit7579f8de7eff422c72e5ec5aeba112c799abc6d1 (patch)
tree9f1cccde8e7a8420025e917f47ba5e35bd78dc26
parent6c51f7a48e689b56363be56ee14f2eddec045576 (diff)
parentc13d7fa7eab0814f80834f9fad3a9cabdc14b798 (diff)
downloadperlweeklychallenge-club-7579f8de7eff422c72e5ec5aeba112c799abc6d1.tar.gz
perlweeklychallenge-club-7579f8de7eff422c72e5ec5aeba112c799abc6d1.tar.bz2
perlweeklychallenge-club-7579f8de7eff422c72e5ec5aeba112c799abc6d1.zip
Merge pull request #862 from Doomtrain14/master
Added perl5 solution ch#32-2
-rw-r--r--challenge-032/yet-ebreo/perl5/ch-2.pl51
1 files changed, 51 insertions, 0 deletions
diff --git a/challenge-032/yet-ebreo/perl5/ch-2.pl b/challenge-032/yet-ebreo/perl5/ch-2.pl
new file mode 100644
index 0000000000..2a5c12aff6
--- /dev/null
+++ b/challenge-032/yet-ebreo/perl5/ch-2.pl
@@ -0,0 +1,51 @@
+#!/usr/bin/perl
+# 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 feature 'say';
+sub generate_bar_graph {
+ my @keys;
+ my ($data,$opt) = @_;
+ my $longest = 0;
+ my @sorted = sort keys %{$data};
+ for my $word (@sorted) {
+ $longest = length $word if $longest < length $word;
+ }
+
+ @keys = ($opt eq "values")?sort { ${$data}{$b}-${$data}{$a} } @sorted:@sorted;
+
+ for my $word (@keys) {
+ printf ("%${longest}s | %s\n",$word, "####" x ${$data}{$word});
+ }
+}
+
+my $data = { apple => 3, cherry => 2, banana => 1 };
+say "Bar graph sorted by labels:";
+generate_bar_graph($data,"labels");
+say "\nBar graph sorted by values:";
+generate_bar_graph($data,"values");
+=begin
+perl .\ch-2.pl
+Bar graph sorted by labels:
+ apple | ############
+banana | ####
+cherry | ########
+
+Bar graph sorted by values:
+ apple | ############
+cherry | ########
+banana | ####
+=cut \ No newline at end of file