aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xchallenge-031/dave-jacoby/perl5/ch-1.pl38
-rwxr-xr-xchallenge-031/dave-jacoby/perl5/ch-2.pl31
2 files changed, 69 insertions, 0 deletions
diff --git a/challenge-031/dave-jacoby/perl5/ch-1.pl b/challenge-031/dave-jacoby/perl5/ch-1.pl
new file mode 100755
index 0000000000..880fb72d06
--- /dev/null
+++ b/challenge-031/dave-jacoby/perl5/ch-1.pl
@@ -0,0 +1,38 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+use utf8;
+use feature qw{ say state };
+use experimental qw{ postderef signatures switch };
+
+use Try::Tiny;
+
+# notice the slightly more compact header
+
+# TASK #1
+
+# Create a function to check divide by zero error
+# without checking if the denominator is zero.
+
+say div_zero_check( 1, 2 ) ? 'Divide by zero' : 'OK';
+
+say div_zero_check( 1, 0 ) ? 'Divide by zero' : 'OK';
+
+say div_zero_check( 0, 1 ) ? 'Divide by zero' : 'OK';
+
+# If we can't pre-check, we can post-check. Perl will correctly
+# throw an error, so $result will remain 0.
+# Otherwise we check the $result AND the numerator, because
+# 0/4 will still be zero, but will not be an error
+
+sub div_zero_check ( $numerator, $denominator ) {
+ my $result = 0;
+ try { $result = $numerator / $denominator; }
+ catch { 1 };
+
+ if ( $result == 0 && $numerator != 0 ) {
+ return 1;
+ }
+ return 0;
+}
diff --git a/challenge-031/dave-jacoby/perl5/ch-2.pl b/challenge-031/dave-jacoby/perl5/ch-2.pl
new file mode 100755
index 0000000000..50b8c7de62
--- /dev/null
+++ b/challenge-031/dave-jacoby/perl5/ch-2.pl
@@ -0,0 +1,31 @@
+#!/usr/bin/env perl
+
+# use strict;
+# use warnings;
+use utf8;
+
+# TASK #2
+
+# Create a script to demonstrate creating dynamic variable name,
+# assign a value to the variable and finally print the variable.
+# The variable name would be passed as command line argument.
+
+# because variable set as command-line argument, we:
+# * stick with $ARGV[0], to avoid collisions with user input
+# * use Encode to allow Unicode values
+# * set $ARGV[0] if it isn't assigned
+
+use Encode qw{decode_utf8};
+@ARGV = map { decode_utf8( $_, 1 ) } @ARGV;
+$ARGV[0] //= 'scratch';
+
+# I can be a literalist
+${ $ARGV[0] } = 'a value';
+
+# and heredocs, because heredocs
+print <<"END";
+
+$ARGV[0] = ${ $ARGV[0] }
+
+END
+