The Weekly Challenge 031

Divide by Zero & Dynamic Variable Assignment

Solutions on GitHub

Task 1: Divide by Zero Error Check

Create a function to check for a divide-by-zero error without checking if the denominator is zero (i.e. using exception handling).

Example Output

Input: num = 1, div = 0 Output: "ERROR" / "error" Input: num = 6, div = 2 Output: 3 / 3.0

Logic

Instead of manually asserting if the divisor is 0 using conditional checks (e.g. if ($div == 0)), we attempt to execute the division inside an exception handling block. In Perl, we use the classic and robust Try::Tiny module (capturing the error in catch and returning "ERROR"). In Python, we use the standard try-except ZeroDivisionError block to cleanly catch division by zero.

Perl Solution

ch-1.pl

use Try::Tiny; sub divide_test ( $num, $div ) { my $result; try { $result = $num / $div; } catch { $result = "ERROR"; }; return $result; }

Python Solution

ch-1.py

def check_divide(num: Union[int, float], div: Union[int, float]) -> Union[float, str]: try: return num / div except ZeroDivisionError: return "error"

Task 2: Dynamic Variable Assignment

Create a script to demonstrate creating dynamic variable name, assigning a value to the variable, and finally printing the variable. The variable name is passed as command line argument.

Example Output

Input: $name = "my_dynamic_var", $value = "hello_world" Output: Assigned $my_dynamic_var = hello_world

Logic

In Perl, variable names can be dynamically resolved using symbolic references by temporarily disabling reference strictures: no strict 'refs'. We then assign via ${$var_name} = $val. In Python, variables in the local or global namespace can be dynamically accessed and assigned via dictionary access on globals() or passing a custom scope mapping.

Perl Solution

ch-2.pl

sub assign_variable ( $var_name, $val = 'test' ) { no strict 'refs'; ## no critic (TestingAndDebugging::ProhibitNoStrict) ${$var_name} = $val; return ${$var_name}; }

Python Solution

ch-2.py

def assign_dynamic_var(name: str, value: Any, scope: dict[str, Any] | None = None) -> Any: target_scope = globals() if scope is None else scope target_scope[name] = value return target_scope[name]