Dynamically Generate Variable Names in Perl

NOTE: this is not recommended, but it is a powerful feature which can be useful.

We can generate dynamic variable names in Perl using Symbolic References. To use the feature, we have to turn off strict refs.

The code below generates the variable names ‘var1’, ‘var2’, ‘var3’ dynamically in a loop as strings, names which can be used as actual variable names with the help of symbolic references.
Of course, hashes should be used instead whenever possible; this is for demonstration.

use strict;
our $var1 = 'a';
our $var2 = 'b';
our $var3 = 'c';

for (my $i = 1; $i < 4; $i++) {
  my $variableName;
    # Symbolic References require 'no strict'.
    no strict 'refs';
    $variableName = ${'var' . $i}; # Dynamic name.
  print $variableName . "\n";




Istanbul Ignore Syntax for Jest Code Coverage

Istanbul is the tool Jest uses to calculate test coverage. Sometimes we need to exclude some code from the coverage calculations. This is done with special comments which are parsed by Istanbul. There are a few variations of the syntax.

Ignore a Function

/* istanbul ignore next */
const f = () => {
  return 'abc'

This will exclude the entire function from code coverage requirements.

Ignore a Whole File

/* istanbul ignore file */

... file contents ...

Use this as the first line of the file. The entire file will be excluded from code coverage.

Ignore a Method in a Class

class A {
  f() {
    console.log("f called")
  /* istanbul ignore next */ g() {
    console.log("g called")

The comment must be on or above the line defining the method so it is not part of the coverage requirement.

Function Inside an Exported Object

Sometimes we have a module which exports some functions inside an object.
The example below shows how to ignore these for coverage. The comment must be right before the function definition.

module.exports = {
  f: () => { 
    console.log('f called')
  g: /* istanbul ignore next */ () => {
    console.log('g called')
  h: /* istanbul ignore next */ async () => {
    console.log('h called')

Note that for async functions we must place the comment before the async keyword.

Ignore Else Cases

To ignore just the else case of a block of code for test coverage, use the syntax as below.

function f(x) {
  /* istanbul ignore else */
  if (x >= 0) {
  } else { // Ignore this block for code coverage.

NOTE: the ignore-else comment is placed above the if statement to ignore the else case for coverage.