Perl Weekly Challenge 031
Perl Weekly Challenge has started to see "guest" entries in other languages. Of course, the focus of the challenges will always be Perl and Raku but I like the idea of entries in other languages being made. If nothing else, it's a good way to maintain a good perspective on how these ideas may be implemented elsewhere. In this spirit I have added some C++ entries this week. As my time allows I would like to maintain this as something I do going forward.
Create a function to check divide by zero error without checking if the denominator is zero.
All solutions use some variant of try/catch in that they perform the division and then try to gracefully handle what happens. The C++ solution of catching a SIGFPE could have been implemented in all three but I chose to explore the variety of possibilities.
The traditional Perl way to do this to use an eval block and then test $@ to see if an error was thrown. Modules exist on can to allow for try/catch syntax if you'd prefer.
$ perl perl5/ch-1.pl
caught an error: Illegal division by zero at perl5/ch-1.pl line 7.
Raku has try/catch syntax built in.
$ perl6 raku/ch-1.rk
caught an error: X::Numeric::DivideByZero
C++ has try/catch syntax however divide by zero is not one of the standard exceptions. To handle this error within your code you need to configure a signal handler to detect that a FPE (Floating Point Error) signal has been generated.
caught an error
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.
Somewhat surprisingly Raku and C++ are similar in that they either do not allow symbol table manipulation at runtime (Raku) or remove variable names at runtime and disallow symbol table manipulation at compile time (C++). The solutions in both cases are to dynamically generate some code. The C++ solution uses the pre-processor for this and Raku will generate a small module which is then required and subsequently deleted. Perl most easily allows this with symbolic references.
$ perl perl5/ch-2.pl pwc 31
The value of $pwc is 31.
$ perl6 raku/ch-2.rk pwc 31
The value of $pwc is 31.
The pre-processor is able to convert a bare word to a quoted string using the # operator but only for macro parameters. This requires creating the QUOTE macro. An additional macro MAKE_NAME is required to make this work in order to get VARIABLE expanded properly. The "command line argument" is actually using -D to define a macro value for the pre-processor. This is admittedly a very contrived way of doing things but this is the only way we can somewhat claim to dynamically create a variable name in C++.
$ g++ -DVARIABLE="pwc" -DVALUE=31 -o cxx/ch-2 cxx/ch-2.cxx
The value of pwc is 31.