diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2019-10-24 11:52:50 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2019-10-24 11:52:50 +0100 |
| commit | f3da502c02552a19c58e68d457944fc800a1f75c (patch) | |
| tree | 21c3e6516e21b621322cd93bbf6a83b9263e640b | |
| parent | c294595bb51393fed1fddfb8d43bae4cbf0683e0 (diff) | |
| parent | 5ca4f802315a63f5c195680b8bf4c7488cae5991 (diff) | |
| download | perlweeklychallenge-club-f3da502c02552a19c58e68d457944fc800a1f75c.tar.gz perlweeklychallenge-club-f3da502c02552a19c58e68d457944fc800a1f75c.tar.bz2 perlweeklychallenge-club-f3da502c02552a19c58e68d457944fc800a1f75c.zip | |
Merge pull request #833 from jacoby/master
Challenge 31!
| -rwxr-xr-x | challenge-031/dave-jacoby/perl5/ch-1.pl | 38 | ||||
| -rwxr-xr-x | challenge-031/dave-jacoby/perl5/ch-2.pl | 31 |
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 + |
